
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
114
|
Chapter 5: Operators
Operator Associativity
As we’ve just seen, operator precedence indicates the pecking order of operators:
those with a higher precedence are executed before those with a lower precedence.
But what happens when multiple operators occur together and have the same level of
precedence? In such a case, we apply the rules of operator associativity, which indi-
cate the direction of an operation. Operators are either left-associative (performed
left to right) or right-associative (performed right to left). For example, consider this
expression:
a = b * c / d
The * and / operators are left-associative, so the * operation on the left (b * c)is
performed first. The preceding example is equivalent to:
a = (b * c) / d
instanceof 10 left to right check an object’s class
== 9 left to right equality
!= 9 left to right not equal to
=== 9 left to right strict equality
!= = 9 left to right strict inequality
& 8 left to right bitwise AND
^ 7 left to right bitwise XOR
| 6 left to right bitwise OR
&& 5 left to right logical AND
|| 4 left to right logical OR
?: 3 right to left conditional
= 2 right to left assignment
+= 2 right to left add and reassign
–= 2 right to left subtract and reassign
*= 2 right to left multiply and reassign
/= 2 right to left divide and reassign
%= 2 right to left modulo ...