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.equalsis identity;String, wrappers, records and collections override it to compare contents.
String s1 = new String("java"), s2 = new String("java");
s1 == s2; // false
s1.equals(s2); // true
"java".equals(input); // safe even when input is nullThe 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.
