Quick revision
The short answer
For objects, == compares references, so it is true only when both sides are the very same object, while equals() compares logical value when the class overrides it. System.identityHashCode() returns the hash that Object.hashCode() would give, ignoring any override. IdentityHashMap uses == and identityHashCode instead of equals() and hashCode(), which suits graph traversal, serialization and tracking visited objects, but deliberately breaks the general Map contract.
What to remember
In this answer, we saw that == compares references and equals() compares values when a class overrides it, and that the Integer cache makes == on boxed numbers a classic trap. == is right for enums, because each constant is a guaranteed singleton, and it is null-safe there. System.identityHashCode() returns the identity-based hash that Object.hashCode() would give, ignoring overrides. IdentityHashMap uses == and identityHashCode, which suits visited sets and object-graph algorithms, but it deliberately breaks the Map contract, so it stays inside the code that needs it.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
For objects, == compares references, so it is true only when both sides are the very same object, while equals() compares logical value when the class overrides it. System.identityHashCode() returns the hash that Object.hashCode() would give, ignoring any override. IdentityHashMap uses == and identityHashCode instead of equals() and hashCode(), which suits graph traversal, serialization and tracking visited objects, but deliberately breaks the general Map contract.
Why this question is asked
Mixing up == and equals() is one of the oldest Java bugs, and it still causes real failures: a comparison that works in a unit test with small cached Integers and fails in production with larger values. Interviewers start with the basic difference and then move to identityHashCode and IdentityHashMap to see whether we understand identity as a concept, not just a rule to memorize. In this answer, we will recap identity and equality, see the classic traps, look at what identityHashCode returns, and then see where IdentityHashMap is the right tool and where it is not.
1A Quick Recap: Identity and Equality
Every object on the heap has an identity: it is one particular object, distinct from every other, even another object with exactly the same fields. A variable of a reference type holds a reference to an object, a kind of pointer. When we write a == b with two references, Java compares the references themselves, so the result is true only if a and b point to the same object.
Equality is a different idea: two objects are equal when they represent the same value, such as two String objects that both contain hello. Object.equals() by default is just ==, but classes like String, Integer, LocalDate and every record override it to compare their contents.
The Integer lines show why == on objects is dangerous. Autoboxing reuses cached Integer objects for values from -128 to 127, so == happens to work for small numbers and fails for larger ones. A test with id 5 passes and production with id 5000 fails. The rule is simple: for objects, compare values with equals(), or with Objects.equals(a, b) when either side may be null.
2When == Is the Right Comparison
There are cases where identity is exactly what we want. The most common is enums. Each enum constant is a single object created once when the enum class initializes, and Java guarantees no other instance can ever be created, not through new, reflection or deserialization. So == is correct and is the preferred way to compare enum values.
Notice the extra benefit: == is null-safe, while calling equals() on a null reference throws. That makes == on enums both correct and slightly safer. The other legitimate uses of == are checking for null, the this == o shortcut at the top of an equals() method, and the cases where we really care about one specific object, which brings us to identityHashCode.
3What System.identityHashCode Returns
Object.hashCode() gives every object a hash based on its identity, and classes that override equals() override hashCode() to match. System.identityHashCode(obj) always returns the original, identity-based hash, the value Object.hashCode() would have returned, even if the class overrides hashCode(). For null it returns 0.
In HotSpot the identity hash is generated the first time it is requested and stored in the object's header, so it stays the same for the object's whole life, even when the garbage collector moves the object. It is not a memory address. Two different objects can, rarely, have the same identity hash, so it is a hash and not a unique id.
4How IdentityHashMap Uses Identity
IdentityHashMap is a Map that replaces equals() with == and hashCode() with System.identityHashCode(). Two keys are the same key only if they are the same object. Internally it is also built differently from HashMap: it stores keys and values next to each other in one flat array and resolves collisions by linear probing, trying the next slot, so it creates no node objects per entry.
| HashMap | IdentityHashMap | |
|---|---|---|
| Same key when | k1.equals(k2) | k1 == k2 |
| Hash used | key.hashCode() | System.identityHashCode(key) |
| Storage | array of buckets with nodes | one flat array, keys and values alternate |
| Collisions | linked nodes, trees when crowded | linear probing |
| Good for | general lookup by value | visited sets, object graphs, proxies |
This is exactly what some algorithms need. When we walk an object graph, for example in a serializer, a deep-copy utility or a cycle detector, we must remember which objects we have already visited. If two distinct objects happen to be equal, a HashMap would treat the second one as already visited and skip it, corrupting the copy. Worse, an object whose hashCode() depends on mutable fields might change hash while we walk. Identity is stable and is the right notion of visited, which is why Java serialization uses an identity-based handle table internally.
5Why IdentityHashMap Breaks the Map Contract
The Map interface says a map contains a key if it contains some k with key.equals(k). IdentityHashMap's documentation states plainly that it intentionally violates this general contract. That matters as soon as we use it for normal keys: a lookup with an equal but different String finds nothing.
So we use IdentityHashMap only where identity is the real requirement, keep it private inside the algorithm that needs it, and never pass it to code that expects normal Map behaviour. When we need a visited set rather than a map, Collections.newSetFromMap(new IdentityHashMap<>()) gives an identity-based Set.
6Follow-up questions
Why does == work on string literals but not on new String()?
String literals are interned: the JVM keeps one String object per literal value in the string pool, so two identical literals refer to the same object and == is true. new String() always creates a new object. Code should never rely on interning for comparisons; equals() is correct in every case.
Can identityHashCode change during an object's life?
No. Once generated it is stored with the object and survives garbage collection moves. It is not guaranteed to be unique, though, so two objects may share one, which is why IdentityHashMap still compares with == after hashing.
Is == correct for records or value-based classes like LocalDate?
No. Records and value-based classes compare by value through equals(), and the JDK documents that code must not rely on the identity of value-based class instances. Future Java versions may make such types identity-free, so == on them is a bug waiting to happen.
7Conclusion
In this answer, we saw that == compares references and equals() compares values when a class overrides it, and that the Integer cache makes == on boxed numbers a classic trap. == is right for enums, because each constant is a guaranteed singleton, and it is null-safe there. System.identityHashCode() returns the identity-based hash that Object.hashCode() would give, ignoring overrides. IdentityHashMap uses == and identityHashCode, which suits visited sets and object-graph algorithms, but it deliberately breaks the Map contract, so it stays inside the code that needs it.
Open with
For objects, == compares references, so it is true only when both sides are the same object. equals compares logical value if the class overrides it, as String, the wrappers and records do; otherwise it falls back to ==.
Then, if they want more
The classic trap is boxed numbers: Integer caches minus 128 to 127, so == passes in tests with small ids and fails with large ones, so I always use equals or Objects.equals. The one place I prefer == is enums, because each constant is a singleton the JVM guarantees, and == is also null-safe there.
System.identityHashCode returns the hash Object.hashCode would give for that object, ignoring any override, and zero for null; it is stable for the object's life but not unique. IdentityHashMap uses == and identityHashCode instead of equals and hashCode, with keys and values in one array and linear probing.
I use it when identity is the real requirement, like tracking visited objects when walking an object graph in a serializer or deep copy, where two equal but distinct objects must both be processed. Its documentation says it intentionally violates the Map contract, so I keep it private to that algorithm and never use it for ordinary keys.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Explain the difference between == and equals for objects. What does...": https://scrivio-interview-library.netlify.app/java/object-contracts/7da34dc2f9/
Java fundamentals, question 1 of 16
More in Object methods and contracts