Java Reference ยท Operators
Java operator precedence
Reference table of Java operator precedence and associativity from postfix to assignment, with examples of common surprises and when to add parentheses.
Operator precedence decides which operators in an expression are applied first. Associativity breaks ties between operators of the same level: most binary operators group left to right, while assignment, the conditional operator and unary operators group right to left.
Precedence only controls grouping, not evaluation order. Java always evaluates operands from left to right, so in f() + g() * h() the calls happen as f, g, h, and only then is the product computed.
int r = 2 + 3 * 4; // 14, same as 2 + (3 * 4)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Precedence table
From highest to lowest. Operators on the same row have equal precedence.
| Level | Operators | Associativity |
|---|---|---|
| 1 | postfix x++ x--, member . , array [], call () |
left to right |
| 2 | prefix ++x --x, unary + - ~ !, cast (T), new |
right to left |
| 3 | * / % |
left to right |
| 4 | + - (including string +) |
left to right |
| 5 | << >> >>> |
left to right |
| 6 | < > <= >= instanceof |
left to right |
| 7 | == != |
left to right |
| 8 | & |
left to right |
| 9 | ^ |
left to right |
| 10 | | |
left to right |
| 11 | && |
left to right |
| 12 | || |
left to right |
| 13 | ?: |
right to left |
| 14 | -> lambda, = += -= *= /= %= &= ^= |= <<= >>= >>>= |
right to left |
Usage notes
&,^and|rank below==.x & 1 == 0parses asx & (1 == 0)and does not compile for anintx. Parenthesize:(x & 1) == 0.- Shifts rank below
+.1 << 2 + 1is1 << 3. &&ranks above||. Add parentheses when mixing them, so readers need not recall the rule.- String
+and numbers are the same level, evaluated left to right, so1 + 2 + "3"is"33". - Casts bind tighter than binary operators:
(double) a / bcastsaonly. - Unary minus on a literal:
-2 * -3is fine, but- -4needs the space (--4is a decrement and does not compile on a literal). - When in doubt, use parentheses. They cost nothing and document intent.