Skip to content
Free public beta until December 4, 2026: every course is open, no card needed. After that, the first chapter of each course stays free and full access is a one-time $39 ($19 for up to 100 founding members chosen for helpful feedback). Your progress is kept. How the beta works

Equality in Java

== on primitives and on references, equals and hashCode, records, strings, boxed numbers and doubles: which comparison each kind of value needs.

Ask what kind of value is on each side.

  • Two primitives (int, char, boolean) → == compares the values. Fine.
  • Two doubles that came out of a calculation → never ==; compare the difference with a tolerance, or use BigDecimal for exact decimals.
  • Two references → == asks "the same object?", which is rarely the question. equals asks "the same value?".
  • Strings → always equals (or equalsIgnoreCase). Text from input, substring or + is a new object, so == fails on equal text.
  • Boxed numbers (Integer, Long) → equals. == happens to work from -128 to 127, because those boxes are cached, and fails above.
  • Your own class → a record gets value equality for free. A class must override equals AND hashCode together, or HashSet and HashMap misbehave.
  • Sorted collections (TreeSet, TreeMap) → they use compareTo or the Comparator, not equals, to decide what counts as a duplicate.

== and what it compares

== and != on primitives.

A reference variable holds an arrow to an object; == compares arrows.

What a String (or other object) variable holds, pointing at an object stored elsewhere.

What a reference variable holds, and what == compares for objects.

The small difference within which two computed doubles are treated as equal.

Example

Math.abs(total - 0.3) < 1e-9

How close two doubles must be to count as equal.

Value equality

equals compares text; == compares references.

The shared store that lets equal string literals be one object.

Why == sometimes seems to work on string literals, and why that can't be relied on.

Overriding equals correctly, and why hashCode must follow.

Equal objects must have equal hash codes, and equals must be reflexive, symmetric, transitive, consistent and false for null.

Example

Override equals without hashCode, and set.contains(copy) returns false.

Equal objects must have equal hash codes.

Section

Records

Value equality generated from the components.

The shared Integer objects for -128 to 127 that boxing reuses instead of allocating.

Example

Integer a = 128, b = 128; then a == b is false, a.equals(b) is true.

The -128 to 127 boxes that make == on Integers look like it works.

Ordering instead of equality

The default order compareTo defines.

compareTo's order, which sorted collections use to spot duplicates.

Section

Sets

HashSet uses equals and hashCode; TreeSet uses compareTo.