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.
String a = new String("java"); a == "java"; // false (different objects) a.equals("java"); // true
Try it
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.
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
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()inObjectis identical to==. A class gets value equality only if it overridesequals()(andhashCode()). 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.
Integercaches -128 to 127 by default, so==works for small values and fails for large ones. Compare withequals()or unbox. - Call
equals()on a non-null value ("x".equals(s)) or useObjects.equals()to avoidNullPointerException. - The contract:
equals()must be reflexive, symmetric, transitive, consistent and false fornull; equal objects must have equal hash codes. - Arrays inherit identity equality. Use
Arrays.equals, ordeepEqualsfor nested arrays. equals()of different wrappers is false:Integer.valueOf(1).equals(1L)isfalse.