Precedence & associativity in Java
Which operator binds first and left-to-right evaluation of operands.
i * (i = 5) with i = 2: is it 25 or 10? Parentheses go first, right? Java says 10. Let's see why.The precedence ladder
Operators higher on the ladder bind first. That's why 2 + 3 * 4 is 14, and a < b && c < d needs no parentheses.
* / % (binds first)
+ -
< > <= >=
== !=
&&
||
? :
= += -= (binds last)Your turn
What does this print?
System.out.println(true || false && false);truefalse
Show the answer
&& binds tighter than ||, so this is true || (false && false) = true. Reading strictly left to right would give false.
Associativity breaks ties
Same precedence? Associativity decides. Most operators group left to right: 10 - 4 - 3 is (10 - 4) - 3 = 3. Assignment groups right to left: a = b = 4 is a = (b = 4).
Your turn
What does this print?
System.out.println(100 / 10 / 5);2500
Show the answer
/ groups left to right: (100 / 10) / 5 = 10 / 5 = 2. Grouping from the right would give 100 / 2 = 50.
Evaluation order is separate
Precedence only decides grouping. Independently, Java always evaluates operands left to right before applying an operator. Parentheses don't make anything run earlier.
Parentheses don't jump the queue
Java reads the left operand i first (2), then evaluates (i = 5), which gives 5. So r is 2 * 5 = 10.
int i = 2;
int r = i * (i = 5);
// r is 10, not 25In real projects
Nobody memorizes the whole table. Professionals add parentheses when mixing && with ||, or bit operators with comparisons: flags & MASK != 0 doesn't even compile, because != binds first.
Key takeaways
- * / % → + - → < > → == != → && → || → ?: → =
- 10 - 4 - 3 is (10 - 4) - 3
- a = b = 4 is a = (b = 4)
- Left operand is always evaluated before the right
In C, i++ + i++ is undefined behavior: different compilers may give different answers. Java's spec fixes the order (operands left to right), so every JVM agrees.
Practice questions
What does this print?
System.out.println(10 - 4 - 3);- 9
- 3
- -3
- 17
Check your answer
3. - is left-associative, so it's (10 - 4) - 3 = 3, not 10 - (4 - 3) = 9.
What does this print?
int a, b;
a = b = 4;
System.out.println(a + b);- 4
- Compile error
- 8
- 0
Check your answer
8. Assignment is right-associative: b = 4 runs first and its value 4 is then assigned to a.