Skip to content
UniCircle
EasyConceptualStrings

== vs equals() (and the hashCode contract)

Question JAVA-STR-022

What is the difference between == and equals()? What is the contract between equals() and hashCode()?

Show the explanation
  • == on references checks identity: are both variables pointing at the same object? On primitives it compares values.
  • equals() checks logical equality as defined by the class. Object.equals is identity; String, wrappers, records and collections override it to compare contents.
Java
String s1 = new String("java"), s2 = new String("java");
s1 == s2;          // false
s1.equals(s2);     // true
"java".equals(input);   // safe even when input is null

The contract: if a.equals(b) is true, then a.hashCode() == b.hashCode() must also be true. (Equal hash codes do not imply equality.) equals must also be reflexive, symmetric, transitive and consistent, and return false for null.

If you override equals but not hashCode, two "equal" objects can land in different HashMap/HashSet buckets, so lookups fail and sets keep duplicates. Generate both together, use Objects.equals / Objects.hash, or use a record, which does it for you.

Original UniCircle question. Last reviewed 22 Oct 2026.