unkletayo
5

Objects, equality and identity

What new does, why == lies, and the contract that HashMap depends on.

Adetayo Akinsanya2026-06-307 min read

  • Java
  • Core Java
  • OOP
  • equals
  • hashCode

Part 5 of the series.Read Methods and the call stack (Part 4) first if you have not.

In this article (7 sections)
  1. What new does
  2. Identity: the address is the identity
  3. Equality: comparing content
  4. The hashCode contract
  5. State, behavior, identity
  6. The string pool
  7. Prediction exercise
Account a1 = new Account("Adetayo", 5000);
Account a2 = new Account("Adetayo", 5000);
System.out.println(a1 == a2);

This prints false. Same class, same field values, different result. If you expected true, or you’re not sure why it’s false, this article is the explanation.

What new does

The new keyword creates an object in three steps.

First, the JVM allocates memory on the heap for the new object. The amount of memory depends on the class’s fields. An Account with two fields (a String reference and an int) needs space for those two slots plus an object header. The header stores bookkeeping information the JVM needs: the type of the object (a pointer to its class metadata), and flags used by the garbage collector and synchronisation mechanism.

Second, the JVM runs the constructor. The constructor’s job is to put the new object into a valid initial state. It can set fields, call other methods, or call a parent class constructor with super(...). The constructor receives this, a reference to the newly allocated object, as its implicit first argument.

Third, the new expression evaluates to the address of the new object. That address is what gets stored in your reference variable.

Account a1 = new Account("Adetayo", 5000);

The Account object is on the heap. a1 holds its address. Every call to new Account(...) allocates a new, distinct object at a new address, even if the constructor arguments are identical.

Identity: the address is the identity

An object’s identity is its location in memory. Two objects are the same object if and only if they occupy the same memory location, meaning they have the same address.

The == operator on reference variables checks addresses. a1 == a2 asks: does a1 hold the same address as a2? Since new Account(...) was called twice, two separate objects were allocated at two different addresses. a1 == a2 is false.

This is true even if every field has the same value:

Account a1 = new Account("Adetayo", 5000);
Account a2 = new Account("Adetayo", 5000);
// a1.name == a2.name might be true (string pool, discussed below)
// a1.balance == a2.balance is true (same int value)
// a1 == a2 is false (different heap addresses)

Identity is about which object, not what values it holds.

A reference variable assigned null holds no address at all. null == null is true; a1 == null is false for any non-null reference.

Equality: comparing content

Identity is not always what you want. If you have two separate Account objects representing the same account, perhaps one fetched from a database and one held in memory, you might consider them equal if their account IDs match, regardless of whether they’re the same Java object.

This is what equals() is for.

Every class inherits equals(Object other) from java.lang.Object. The default implementation provided by Object checks identity: return this == other. It’s the same as ==.

To compare content, you override equals() in your class:

public class Account {
    private final String id;
    private int balance;

    public Account(String id, int balance) {
        this.id = id;
        this.balance = balance;
    }

    @Override
    public boolean equals(Object other) {
        if (this == other) return true;
        if (!(other instanceof Account)) return false;
        Account that = (Account) other;
        return this.id.equals(that.id);
    }
}

Now a1.equals(a2) checks IDs rather than addresses. Two Account objects with the same ID are equal according to this method, even though a1 == a2 is still false.

The hashCode contract

Whenever you override equals(), you must also override hashCode(). This is not a style suggestion. It’s a contract. The JLS (§11.2 of the Object specification, via java.lang.Object API documentation) states:

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

HashMap and HashSet depend on this contract. When you call map.get(key), the map first calls key.hashCode() to find the right bucket in its internal array, then uses equals() to find the matching entry within that bucket. If two equal objects have different hash codes, get will look in the wrong bucket and not find the entry, even though it’s there.

Here’s the failure mode:

public class BrokenAccount {
    private final String id;
    // ... constructor ...

    @Override
    public boolean equals(Object other) {
        if (!(other instanceof BrokenAccount)) return false;
        return this.id.equals(((BrokenAccount) other).id);
    }
    // hashCode NOT overridden — inherits Object's default, which uses identity
}

Map<BrokenAccount, Integer> ledger = new HashMap<>();
BrokenAccount acc = new BrokenAccount("A001");
ledger.put(acc, 5000);

BrokenAccount lookup = new BrokenAccount("A001");
System.out.println(ledger.get(lookup));  // null — not found!

acc.equals(lookup) returns true (same ID). But acc.hashCode() and lookup.hashCode() return different values (identity-based defaults from two different objects). The map stores the entry in the bucket for acc.hashCode(), then looks for it in the bucket for lookup.hashCode(). Different buckets. Entry not found.

The fix: override hashCode() based on the same fields that equals() uses.

@Override
public int hashCode() {
    return id.hashCode();
}

Now equal accounts produce equal hash codes, and HashMap works correctly.

Modern Java makes this easier. Records automatically generate correct equals() and hashCode() implementations based on all their components. And IDE tools can generate them for regular classes. But you should understand why the contract exists before relying on generated code to satisfy it.

State, behavior, identity

It’s worth naming these three dimensions explicitly, because they describe what an object is.

State is the current values of the object’s fields. An Account with balance 5000 has different state from one with balance 3000, even if they’re otherwise identical.

Behavior is what the object’s methods do. deposit(100) and withdraw(50) are behaviors. Two objects of the same class have the same behaviors.

Identity is what distinguishes this object from all others. In Java, identity is the object’s address. It doesn’t change over the object’s lifetime (from Java code’s perspective, the GC may move objects internally, but it updates all references to maintain consistency).

Two objects can share state and class (identical fields, same type) and still be distinct objects with separate identities. This is exactly a1 and a2 above.

The string pool

String literals are a special case worth knowing.

When the compiler sees "hello" as a literal in source code, it records the string in the class’s constant pool. At runtime, the JVM maintains a string pool, a table of interned strings. The first time "hello" is needed, an object is created and added to the pool. The next time "hello" is needed from any class, the same object is returned.

This means string literals with the same content often share the same object:

String a = "hello";
String b = "hello";
System.out.println(a == b);   // true — same pooled object

But new String("hello") bypasses the pool and always allocates a new object:

String c = new String("hello");
String d = new String("hello");
System.out.println(c == d);   // false — two distinct objects
System.out.println(c.equals(d));  // true — same character sequence

This is why you should compare strings with equals(), not ==. Code that works in a test might break in production if the string was constructed differently and isn’t pooled. equals() on String compares the characters; == compares addresses.

Prediction exercise

public class Point {
    int x, y;
    Point(int x, int y) { this.x = x; this.y = y; }
}

Point p1 = new Point(3, 4);
Point p2 = new Point(3, 4);
Point p3 = p1;

System.out.println(p1 == p2);
System.out.println(p1 == p3);
System.out.println(p1.equals(p2));
System.out.println(p1.equals(p3));

Predict each output before running. Then: if you override equals() in Point to compare x and y fields, what do p1.equals(p2) and p1.equals(p3) return? And if you override equals() but forget hashCode(), what breaks?

Questions or corrections

Found a mistake or have a question about this breakdown? Reach out directly.

Reply on X (@unkletayor)Email feedback