;
It is important that all developers have an understand of operator precedence as it defines the order in which operators are used. Most people will have come across operator precedence in mathematics but software takes it to the next level. An example of why understanding precednce is important is this simple statement:
x = 1 + 2 * 3;
What is the value of x. Is is seven or nine? The correct answer is seven because the multiplier has a higher precedence than the addition operator and so the multiplication is carried out first. The table below shows the full list of operator precedence in Java.
| Priority | Operator | Operation Name | Associativity | Example |
|---|---|---|---|---|
| 1 | [] | Array Index | Left | foo[ 10 ]; |
| () | Method Call |
foo.bar(); | ||
| . | Member Access | foo.bar; | ||
| 2 | ++, -- |
Pre/Post Increment and Decrement | Right | x++ |
| +, - |
Unary plus and minus | -x | ||
| ~ | bitwise NOT | ~x | ||
| ! | boolean (Logical) NOT | boolean x = !y; | ||
| (type) | Type Cast |
Foo f = (Foo)Bar; | ||
| new | Object Creation |
new Foo(); |
||
| 3 | *, /, % |
Multiplication, Division, Remainder |
Left |
1 * 2 / 3 |
| 4 | +, - |
Addition, Subtraction |
Left |
1 + 2 - 3 |
| + | String Concatenation |
"foo" + "bar" |
||
| 5 | <<, >> | Signed Bit Shift Left, Right |
Left | x >> y |
| >>> | Unsigned Bit Shift Right |
x >>> y | ||
| 6 | <. <= | Less Than, Less Than Or Equal | Left | x <= y |
| >, >= | Greater Than, Greater Than Or Equal | x >= y | ||
| instance of | Instance Comparison | foo instance of bar | ||
| 7 | == | Equal To | Left | foo == bar |
| !- | Not Equal To | foo != bar | ||
| 8 | & | Bitwise AND | Left | x & y |
| & | Boolean (Logical) AND | x &y | ||
| 9 | ^ | Bitwise XOR | Left | x ^ y |
| ^ | Boolean(Logical) XOR | x ^y | ||
| 10 | | | Bitwise OR | Left | x | y |
| | | Boolean (Logical) OR | x | y | ||
| 11 | && |
Boolean (Logical) AND |
Left |
x && y |
| 12 | || |
Boolean (Logical) OR |
Left |
x || y |
| 13 | ?: |
Ternary Operator |
Right |
foo ? bar : baz |
| 14 | = | Assignment | Right | x = y |
| *=, /=, +=, -=, %=, <<=, >>=, >>>=, &=, ^=, |= |
Combination Operations |
x += y |