Operators and Assignments - Precedence
| Operator precdence (JPL pg 378) |
| Operator type |
Operators |
| Postfix |
[] . (params) expr++ expr-- |
| Unary |
++expr --expr +expr -expr ~ ! |
| Creation or Cast |
new (type)expr |
| Multiplicative |
* / % |
| Additive |
+ - |
| Shift |
<< >> >>> |
| Relational |
< > >= <= instanceof |
| Equality |
== != |
| Bitwise AND |
& |
| Bitwise exclusive OR |
^ |
| Bitwise inclusive OR |
| |
| Logical AND |
&& |
| Logical OR |
|| |
| Ternary |
?: |
| Assignment |
= += -= *= /= %= >>= <<= >>>= &= ^= |= |
- Precedence can be overridden using parantheses
5 + 3 * 2 // Result: 11
(5 + 3) * 2 // Result: 16
- when two operators of the same precedence are next to each other, associativity rules apply
- all binary operators (except assignment operators) are left-associative
- assignment is right-associative
a - b + c is evaluated as (a - b) + c
5 - 2 + 1 // Result: 4, not 2
a = b = c is evaluated as a = (b = c)
int a;
int b = 5;
int c = 1;
a = b = c; // Result: 1
Possible problem areas
- where boolean expressions are used to control loops
while( v = stream.next() != null )
processValue(v);
according to precedence rules, evaluates as
v = (stream.next() != null )
not the intended
(v = stream.next()) != null
Example Code
|