liveBook · Manning

Reference equality

As explained in 100 Java Mistakes and How to Avoid Them

Reference equality is Java's identity comparison of two references to determine whether they denote the same object.

Reference equality uses Java’s == operator to ask whether two references denote the same object. It is not the usual choice for comparing object contents: equals() may report equivalent objects even when == is false. section 7.0 section 7.1

The boxed-integer trap

Integer i1 = 100; Integer i2 = 100; System.out.println(i1 == i2); // often true Integer i3 = 1000; Integer i4 = 1000; System.out.println(i3 == i4); // may be false Autoboxing commonly reuses cached Integer objects for values from -128 through 127. Larger values may create separate objects, so code that accidentally relies on == can change behavior when its data changes. section 7.1

Avoid accidental identity comparisons with these rules:

  • Use equals() when comparing object values or content. section 7.0 section 7.1
  • Do not infer correctness from a true result with small boxed values; caching can conceal the mistake. section 7.1
  • Remember that Boolean and Byte values are cached during autoboxing, while explicitly constructed wrapper objects can still be distinct. section 7.1
Integer i1 = 100;
Integer i2 = 100;
System.out.println(i1 == i2);    #1

Inspect the minimal boxed-integer example that demonstrates why reference equality can appear to work. section 7.1

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains identity semantics, equals() contrast, wrapper caching, and several concrete failure cases.
Examples
Uses cached and uncached Integer values, explicitly constructed Boolean objects, reflection results, and string comparisons.
What it assumes
Assumes Java object and reference familiarity while clarifying the difference between identity, content, and autoboxing.
What you can do after
Diagnose identity-comparison bugs and replace accidental == checks with appropriate value comparisons.
How it connects
Connects reference equality with equals(), hashCode(), Comparable, Comparator, autoboxing, and object caching.

Also explained in

Compare how 4 books explain reference equality →

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.