Java Language Expressions Operator Precedence


When an expression contains multiple operators, it can potentially be read in different ways. For example, the mathematical expression 1 + 2 x 3 could be read in two ways:

  1. Add 1 and 2 and multiply the result by 3. This gives the answer 9. If we added parentheses, this would look like ( 1 + 2 ) x 3.
  2. Add 1 to the result of multiplying 2 and 3. This gives the answer 7. If we added parentheses, this would look like 1 + ( 2 x 3 ).

In mathematics, the convention is to read the expression the second way. The general rule is that multiplication and division are done before addition and subtraction. When more advanced mathematical notation is used, either the meaning is either "self-evident" (to a trained mathematician!), or parentheses are added to disambiguate. In either case, the effectiveness of the notation to convey meaning depends on the intelligence and shared knowledge of the mathematicians.

Java has the same clear rules on how to read an expression, based on the precedence of the operators that are used.

In general, each operator is ascribed a precedence value; see the table below.

For example:

  1 + 2 * 3

The precedence of + is lower than the precedence of *, so the result of the expression is 7, not 9.

DescriptionOperators / constructs (primary)PrecedenceAssociativity
Instance creation
Field access
Array access
Method invocation
Method reference
primary(expr, ...)
15Left to right
Post incrementexpr++, expr--14-
Pre increment
++expr, --expr,
+expr, -expr, ~expr, !expr,
Right to left
Right to left
Multiplicative* / %12Left to right
Additive+ -11Left to right
Shift<< >> >>>10Left to right
Relational< > <= >= instanceof9Left to right
Equality== !=8Left to right
Bitwise AND&7Left to right
Bitwise exclusive OR^6Left to right
Bitwise inclusive OR|5Left to right
Logical AND&&4Left to right
Logical OR||3Left to right
Conditional1? :2Right to left
= *= /= %= += -= <<= >>= >>>= &= ^= |=
1Right to left

1 Lambda expression precedence is complex, as it can also occur after a cast, or as the third part of the conditional ternary operator.