Friday, March 11, 2005

Operator Precedence

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. Left-associative operators are evaluated from left to right. Right-associative operators are evaluated from right to left.

Precedence Operation Group Associativity
[] . (params) array member access method call left-associative
expr++ expr-- ++expr --expr +expr -expr ~expr !expr post increment post decrement pre increment pre decrement ? ? ? ? unary right-associative
new (type)expr creation type cast non-associative
* / % multiplication division remainder multiplicative left-associative
+ - addition subtraction additive left-associative
<< >> >>> left shift right shift right shift shift left-associative
< > <= >= instanceof less than greater than less or equal greater or equal relational left-associative
== != equal not equal equality left-associative
& and bitwise AND left-associative
^ xor bitwise exclusive OR (XOR) left-associative
| or bitwise inclusive OR left-associative
&& and logical AND left-associative
|| or logical OR left-associative
? : conditional conditional right-associative
= += -= *= /= %= &= ^= |= <<= >>= >>>= assign addition subtraction multiplication division remainder and or xor shift shift shift assignment right-associative

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.

Consider the program:
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: