Left-to-Right Associativity for Same-Precedence Operators
What you'll learn: How Java decides the order of operations when multiple operators have the same precedence level.
The Core Idea
You've learned that parentheses can override operator precedence, and that multiplication happens before addition. But what happens when you chain operators that have the same precedence? For example, what about 10 - 5 - 2?
Java uses left-to-right associativity for most operators. This means when operators have equal precedence, Java evaluates them from left to right, just like reading English text.
How It Works in Practice
Consider this expression:
int result = 10 - 5 - 2;
Both subtraction operators have the same precedence. Java evaluates from left to right:
- First:
10 - 5=5 - Then:
5 - 2=3 - Final result:
3
Important: This is not the same as 10 - (5 - 2), which would give you 7!
The Reading Analogy
Think of it like reading a sentence from left to right. When you encounter words (operators) of equal importance, you process them in the order you meet them, not all at once.
int a = 20 / 4 / 2; // (20 / 4) / 2 = 5 / 2 = 2
int b = 100 % 30 % 7; // (100 % 30) % 7 = 10 % 7 = 3
Division and modulus operators also follow left-to-right evaluation when chained together.
Key Takeaway: When operators have the same precedence, Java evaluates them from left to right, processing each operation sequentially as it encounters them.