liveBook · Manning

Operator

As explained in 100 Java Mistakes and How to Avoid Them

A Java operator is a language symbol or keyword that performs an operation on one or more operands.

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

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains precedence categories and reference identity, then stops short of covering type-specific bugs beyond wrapper comparisons.
Examples
Uses Java precedence tables and Integer comparisons whose results vary with wrapper-object caching.
What you can do after
Diagnose expression mistakes, enforce evaluation order with parentheses, and choose equals() for object-content comparisons.
How it connects
Connects operators with operator precedence, parentheses, object equality, equals(), autoboxing, and primitive wrapper classes.

Also explained in

Compare how 7 books explain operator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.