A Java operator is a symbol or keyword that performs an operation on one or more operands. Expression bugs often arise when code uses the wrong operator or assumes the wrong evaluation order. section 2.0
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 to check evaluation order before relying on an unparenthesized expression. section 2.1
Avoid these narrowly scoped operator mistakes:
- Do not assume every operator has equal priority. Java evaluates multiplicative operators before additive operators, while parentheses can change the order. section 2.1
- Do not use == when comparing object contents. The operator compares references; equals() is commonly used to compare equivalent contents. section 7.1
- Treat wrapper comparisons as especially dangerous: autoboxing may reuse cached small values, making incorrect reference comparisons appear to work. section 7.1
- Use explicit parentheses when evaluation order matters, and use equals() for content comparison rather than relying on observed caching behavior. section 2.1 section 7.1
Reference equality can pass accidentally
Integer i1 = 1000; Integer i2 = 1000; System.out.println(i1 == i2); This comparison may fail because the references can point to separate objects. A comparison involving small autoboxed values may instead appear correct because those values are cached. The apparent success does not make == a content comparison. section 7.1






