Java.Core.Why do we need equals()? How is it different from the == operation?

In Java, equals() and == serve different purposes when comparing objects.

1. == Operator (Reference Comparison)

  • The == operator compares memory addresses (references) of two objects.
  • It checks whether both variables refer to the same object in memory.
String str1 = new String("Hello");
String str2 = new String("Hello");

System.out.println(str1 == str2); // false (Different objects)

Even though str1 and str2 contain the same text ("Hello"), they are different objects in memory, so == returns false.

However, for primitive types, == compares values:

int a = 10;
int b = 10;
System.out.println(a == b); // true (Same value)

2. equals() Method (Content Comparison)

  • The equals() method is used to compare the contents of two objects.
  • The default implementation in Object class is similar to ==, but many classes override it to perform value-based comparison.

For example, String overrides equals():

String str1 = new String("Hello");
String str2 = new String("Hello");

System.out.println(str1.equals(str2)); // true (Same content)

Here, equals() compares the characters inside the string, not the memory addresses.

When to Use equals()?

You should use equals() when you want to compare the content (logical equality) of objects, rather than their memory locations.

For example, in a custom class:

class Person {
    String name;

    Person(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;  // Same reference
        if (obj == null || getClass() != obj.getClass()) return false;
        Person person = (Person) obj;
        return name.equals(person.name); // Compare names
    }
}

Person p1 = new Person("Alice");
Person p2 = new Person("Alice");

System.out.println(p1 == p2);        // false (Different objects)
System.out.println(p1.equals(p2));   // true (Same content)

Key Differences:

Feature== (Reference Comparison)equals() (Content Comparison)
ComparesMemory addressesObject contents
Default BehaviorChecks if both references point to the same objectSame as == (unless overridden)
Used forPrimitive types, object referencesComparing meaningful content of objects
Overrideable?NoYes (e.g., in String, Integer, and custom classes)

Summary

  • Use == when checking if two references point to the same object.
  • Use equals() when checking if two objects have the same logical content.
  • Always override equals() in your custom classes when logical equality matters.
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.