Course contentsShow
← Java
Lesson 288 of 2,8707. Reference Types and Object FundamentalsFree lesson

The equals Method: Defining Object Equality

Learn how equals compares object content, why Object's default implementation uses ==, and why it must be overridden.

The equals Method: Defining Object Equality

You'll learn how the equals method allows objects to define their own meaning of "being equal."

Why equals Exists

You've seen that == compares memory addresses—it checks if two references point to the exact same object on the heap. But what if you want to know if two different objects have the same meaningful content?

That's where the equals method comes in.

The Default Implementation Problem

Every class in Java inherits an equals method from Object, but by default, it does this:

public boolean equals(Object obj) {
    return (this == obj);  // Just uses ==!
}

So unless overridden, equals behaves exactly like ==—it only returns true if both references point to the same object in memory.

Content-Based Equality

The equals method is designed to be overridden so classes can define equality based on content, not identity. Think of two houses: they might be different buildings (different addresses in memory), but if they have the same floor plan, number of rooms, and dimensions, you might consider them "equal" for your purposes.

String s1 = new String("hello");
String s2 = new String("hello");

System.out.println(s1 == s2);       // false (different objects)
System.out.println(s1.equals(s2));  // true (same content)

The String class overrides equals to compare character sequences, not memory addresses. That's why it works as expected.

When You Must Override

For your own classes, if you want two instances with the same data to be considered equal, you must override the equals method. Otherwise, you're stuck with reference equality.

Key Takeaway:
The equals method defines content-based equality, but Object's default implementation just uses ==. Classes must override equals to compare meaningful data instead of memory addresses.