Discussion
The operators are listed from highest precedence to lowest, in precedence order. Operators on the same row have equal precedence. Operators with higher precedence are evaluated before operators with lower precedence.
Operators of equal precedence are evaluated in order depending on operator associativity. Leftassociative operators are evaluated from left to right. Rightassociative operators are evaluated from right to left.
Precedence  Operation  Group  Associativity 

[]
.
(params) 
array member access method call  leftassociative  
expr++
expr
++expr
expr
+expr
expr
~expr
!expr

post increment post decrement pre increment pre decrement ? ? ? ?  unary  rightassociative 
new
(type)expr 
creation type cast  nonassociative  
*
/
% 
multiplication division remainder  multiplicative  leftassociative 
+
 
addition subtraction  additive  leftassociative 
<<
>>
>>>

left shift right shift right shift  shift  leftassociative 
<
>
<=
>=
instanceof 
less than greater than less or equal greater or equal  relational  leftassociative 
==
!= 
equal not equal  equality  leftassociative 
& 
and  bitwise AND  leftassociative 
^ 
xor  bitwise exclusive OR (XOR)  leftassociative 
 
or  bitwise inclusive OR  leftassociative 
&& 
and  logical AND  leftassociative 
 
or  logical OR  leftassociative 
? : 
conditional  conditional  rightassociative 
=
+=
=
*=
/=
%=
&=
^=
=
<<=
>>=
>>>= 
assign addition subtraction multiplication division remainder and or xor shift shift shift  assignment  rightassociative 
Warning: You should avoid writing code that depends on order of evaluation. Such code is a bad programming practice, because it is hard to understand.
Concept:
expr
and ++expr
has the same precedence.
Java uses the same precedence and associativity of operators as
"The C Programming Language" by Kernighan and Ritche.
class Order { public static void main(String[] args) { int a = 1; int i = ++a + a; System.out.println("i: " + i + ", a: " + a); } }
i: 4, a: 1
If a
has higher precedence than ++a
,
it should be executed before ++a
and the result should be:
int i = ++a + a; // a = 1 i = ++a + 1; a = a  1; // a = 0 a = a + 1; i = 1 + 1; // a = 1 i = 2;
i = 2 and a = 1 is not the answer the program got, and it is obvious that
a
does not have higher precedence than ++a
.
No comments:
Post a Comment