Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Operators

== vs. equals() in Java

Reference for the difference between == and equals() in Java: reference identity versus value equality, strings, boxed types, enums and arrays.

== and equals() answer different questions. For references, == asks "are these two variables pointing at the very same object?" while equals() asks "do these two objects count as equal?" Whether the second answer is yes is defined by the class. For primitives, == simply compares values and equals() does not exist.

Using == where you meant equals() is a classic source of bugs, particularly with String and the wrapper classes. Many such tests happen to pass during development because of caching and string interning, then fail on other data.

Java
String a = new String("java");
a == "java";        // false (different objects)
a.equals("java");   // true

Try it

Java Strings and boxes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Defining equality and arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
a == b            // same object? (values for primitives)
a.equals(b)       // equal by the class's definition
Objects.equals(a, b)   // null-safe equals
Type Use
primitives == (but see Double.compare for NaN and -0.0)
enums ==
String, wrappers, collections, most classes equals()
arrays Arrays.equals() or Arrays.deepEquals()
possibly null references Objects.equals()

Usage notes

  • Default equals() in Object is identical to ==. A class gets value equality only if it overrides equals() (and hashCode()). Records override both automatically.
  • Strings. Literals and compile-time constants are interned, so they share an object; strings built at run time are new objects. Never compare strings with ==.
  • Boxed values. Integer caches -128 to 127 by default, so == works for small values and fails for large ones. Compare with equals() or unbox.
  • Call equals() on a non-null value ("x".equals(s)) or use Objects.equals() to avoid NullPointerException.
  • The contract: equals() must be reflexive, symmetric, transitive, consistent and false for null; equal objects must have equal hash codes.
  • Arrays inherit identity equality. Use Arrays.equals, or deepEquals for nested arrays.
  • equals() of different wrappers is false: Integer.valueOf(1).equals(1L) is false.