Operator Precedence
When an expression has multiple operators (e.g.,
5 + 2 * 3), Java needs to know which one to calculate first. This
is determined by operator precedence.
Why It Matters
Just like in math class (PEMDAS), multiplication happens before addition.
int x = 5 + 2 * 3;
// 2 * 3 = 6
// 5 + 6 = 11
// Result: 11 (NOT 21)
Precedence & Associativity Table
Operators at the top are evaluated first.
| Category | Operators | Associativity |
|---|---|---|
| Postfix | expr++ expr-- |
Left to Right |
| Unary | ++expr --expr +expr
-expr ~ !
|
Right to Left |
| Multiplicative | * / % |
Left to Right |
| Additive | + - |
Left to Right |
| Shift | << >> >>> |
Left to Right |
| Relational | < > <= >=
instanceof
|
Left to Right |
| Equality | == != |
Left to Right |
| Bitwise AND | & |
Left to Right |
| Bitwise XOR | ^ |
Left to Right |
| Bitwise OR | | |
Left to Right |
| Logical AND | && |
Left to Right |
| Logical OR | || |
Left to Right |
| Ternary | ? : |
Right to Left |
| Assignment | = += -= *= etc
|
Right to Left |
Output
Click Run to execute your code
Controlling Order with Parentheses
Parentheses () have the highest precedence. You can use them to
force evaluations in the order you want.
Best Practice: Don't rely on remembering the entire precedence
table. If an expression is complex, use parentheses to make
your intent clear.
a + b * c vs a + (b * c)
Summary
- Operators with higher precedence are evaluated first.
- Multiplication/Division happen before Addition/Subtraction.
- Assignment
=has very low precedence (happens last). - Use parentheses
()to explicitly define the order of operations and improve code readability.
Enjoying these tutorials?