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
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
.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.
Description | Operators / constructs (primary) | Precedence | Associativity |
---|---|---|---|
Qualifier Parentheses Instance creation Field access Array access Method invocation Method reference | name. name( expr) new primary . nameprimary [ expr] primary ( expr, ...) primary :: name | 15 | Left to right |
Post increment | expr++ , expr-- | 14 | - |
Pre increment Unary Cast1 | ++ expr, -- expr,+ expr, - expr, ~ expr, ! expr,( type) expr | 13 | - Right to left Right to left |
Multiplicative | * / % | 12 | Left to right |
Additive | + - | 11 | Left to right |
Shift | << >> >>> | 10 | Left to right |
Relational | < > <= >= instanceof | 9 | Left to right |
Equality | == != | 8 | Left to right |
Bitwise AND | & | 7 | Left to right |
Bitwise exclusive OR | ^ | 6 | Left to right |
Bitwise inclusive OR | | | 5 | Left to right |
Logical AND | && | 4 | Left to right |
Logical OR | || | 3 | Left to right |
Conditional1 | ? : | 2 | Right to left |
Assignment Lambda1 | = *= /= %= += -= <<= >>= >>>= &= ^= |= -> | 1 | Right 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.