Course contentsShow
← Java
Lesson 541 of 2,87013. The Object Class and Common MethodsFree lesson

The equals Method: Reference vs Logical Equality

Understand the difference between == (reference equality) and equals() (logical equality) and why Object's default equals uses ==.

The equals Method: Reference vs Logical Equality

What You'll Learn

You'll discover the crucial difference between comparing object identity with == and comparing object contents with equals().


Two Kinds of Equality

Java distinguishes between two types of equality:

Reference Equality (==): Checks if two references point to the exact same object in memory—like asking "Are these two variables pointing to the same box?"

Logical Equality (equals()): Checks if two objects are meaningfully equivalent—like asking "Do these two boxes contain the same thing?"

The Analogy

Imagine two students with identical backpacks containing the same books and supplies:

  • Using == asks: "Is this literally the same backpack?" (No—two separate backpacks exist)
  • Using equals() asks: "Do these backpacks have the same contents?" (Yes—they're equivalent)

Object's Default equals Behavior

Here's the catch: the Object class implements equals() using == by default! This means unless you override it, equals() only checks reference equality:

// Object's default equals implementation (simplified)
public boolean equals(Object obj) {
    return this == obj;  // Just reference comparison!
}

This works fine for classes where identity matters (like Thread), but for most domain objects, you'll want to override equals() to compare actual content.

Why This Matters

Without overriding equals(), two Person objects with identical names and ages would be considered unequal—even though logically they represent the same person.

Key Takeaway: The == operator checks if two references point to the same object (reference equality), while equals() should check if two objects are logically equivalent—but Object's default equals() just uses ==, so you must override it for meaningful comparisons.