Adverts

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.

PriorityOperatorOperation NameAssociativityExample
 1 [] Array Index  Left foo[ 10 ]; 
()  Method Call
foo.bar(); 
. Member Access  foo.bar; 
 ++, --
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
+, -
Addition, Subtraction
Left
1 + 2 - 3
 + String Concatenation
"foo" + "bar"
<<, >>  Signed Bit Shift Left, Right
Left  x >> y 
>>>  Unsigned Bit Shift Right
x >>> y 
<. <=  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 
==  Equal To  Left  foo == bar 
 !- Not Equal To  foo != bar 
8 Bitwise AND  Left  x & y
Boolean (Logical) AND  x &y
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 

 

Adverts

Donate and Help

Please support this site and
Bandwidth doesn't grow on trees y' know :o)

Adverts

Get Adsense