➗ Operators & Expressions · Beginner

Precedence & associativity in Java

Which operator binds first and left-to-right evaluation of operands.

🧩 The mysteryi * (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)
🔮 Predict it

Your turn

What does this print?

System.out.println(true || false && false);
  1. true
  2. false
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).

🔮 Predict it

Your turn

What does this print?

System.out.println(100 / 10 / 5);
  1. 2
  2. 50
  3. 0
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.

⚠️ The trap

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 25
💼 In the real world

In 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

  1. * / % → + - → < > → == != → && → || → ?: → =
  2. 10 - 4 - 3 is (10 - 4) - 3
  3. a = b = 4 is a = (b = 4)
  4. Left operand is always evaluated before the right
🤯 Did you know?

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);
  1. 9
  2. 3
  3. -3
  4. 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);
  1. 4
  2. Compile error
  3. 8
  4. 0
Check your answer

8. Assignment is right-associative: b = 4 runs first and its value 4 is then assigned to a.

Next: "1" + 2 + 3 is "123", but 1 + 2 + "3" is "33". The + operator leads a double life.