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
Objectclass 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) |
|---|---|---|
| Compares | Memory addresses | Object contents |
| Default Behavior | Checks if both references point to the same object | Same as == (unless overridden) |
| Used for | Primitive types, object references | Comparing meaningful content of objects |
| Overrideable? | No | Yes (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.