Operator precedence determines how Java groups operators in an expression when parentheses do not say otherwise. Familiar arithmetic usually follows expectations, but shifts, bitwise operators, logical operators, and the conditional operator can produce valid code with an unintended value or control path. Parentheses override the default grouping. section 2.0 section 2.1
Table 2.1 Operator precedence in Java
|
Precedence
|
Category
|
Operators
|
|---|---|---|
|
1
|
Postfix
|
++,
--
|
|
2
|
Prefix
|
++,
--,
+,
-,
~,
!
|
|
3
|
Multiplicative
|
*,
/,
%
|
|
4
|
Additive
|
+,
-
|
|
5
|
Shift
|
<<,
>>,
>>>
|
|
6
|
Relational
|
<,
>,
<=,
>=,
instanceof
|
|
7
|
Equality
|
==,
!=
|
|
8
|
Bitwise and
|
&
|
|
9
|
Bitwise xor
|
^
|
|
10
|
Bitwise or
|
|
|
|
11
|
Logical and
|
&&
|
|
12
|
Logical or
|
||
|
|
13
|
Conditional
|
?:
|
|
14
|
Assignment
|
=,
+=,
-=,
*=,
/=,
%=,
&=,
^=,
|=,
<<=,
>>=,
>>>=
|
Use the precedence table when an expression combines unfamiliar operator categories; do not rely on an operator’s apparent meaning to infer its priority. section 2.1
Shift is lower priority than addition
`lo << 16 + hi` is grouped as `lo << (16 + hi)`, not `(lo << 16) + hi`. The result can silently corrupt packed values or hash-code distribution because both groupings are type-correct. Write the intended grouping explicitly. section 2.1.1
Bitwise arithmetic needs explicit intent
`bits & 0xFF00 + 1` becomes `bits & 0xFF01`, so it copies the low bit rather than unconditionally setting it. Prefer the operation that expresses the goal, such as `(bits & 0xFF00) | 1`, and parenthesize mixed bitwise operations for readers. section 2.1.2
Guard every branch of a mixed condition
`index >= 0 && str.charAt(index) == ' ' || str.charAt(index) == '\t'` leaves the tab check outside the nonnegative-index guard because `&&` binds before `||`. Parenthesize the alternatives, or split the condition into simpler statements. section 2.2.1
The conditional operator has very low precedence. In a larger calculation or concatenation, surround `?:` with parentheses or first compute its result in a variable. Prefer library operations when they state the intent directly, such as `Math.max`, `String.repeat`, or `Objects.requireNonNullElse` where appropriate. section 2.2.2 section 2.2.3
Use these prevention rules when precedence is not immediately obvious:
- Avoid mixing arithmetic and bitwise operators in one expression unless the grouping is explicit. section 2.1.2
- Parenthesize every condition that combines `&&` and `||`, or extract predicates, variables, or separate `if` statements. section 2.2.1 section 2.7
- Treat static-analysis warnings as prompts to inspect intent; precedence inspections can be noisy, and adding parentheses that preserve existing semantics may retain a bug. section 2.1.1 section 2.1.2
- Wrap a concatenated string before calling a method on the whole result; otherwise the call applies only to the final string fragment. section 2.4






