In Java, == and .equals() are both used to compare things — but they compare different aspects of objects.
== (Reference Comparison)
== checks whether two references point to the exact same object in memory.
It does NOT check if the contents are equal.
Example:
String a = new String("hello");
String b = new String("hello");
System.out.println(a == b); // false
Even though both contain "hello", they are different objects in memory.
However:
String a = "hello";
String b = "hello";
System.out.println(a == b); // true
Because Java uses the String Pool, both references point to the same object.
.equals() (Content Comparison)
.equals() checks whether two objects are logically equal (same content).
For String, Integer, and many other classes, .equals() is overridden to compare values.
Example:
String a = new String("hello");
String b = new String("hello");
System.out.println(a.equals(b)); // true
Because the contents are the same.
Important Difference Summary
| Feature | == | .equals() |
|---|---|---|
| Compares | Memory address | Object content |
| Works for primitives? | ✅ Yes | ❌ No |
| Works for objects? | ✅ Yes | ✅ Yes |
| Can be overridden? | ❌ No | ✅ Yes |
Special Case: Primitives
For primitive types (int, double, boolean, etc.):
int x = 5;
int y = 5;
System.out.println(x == y); // true
== compares actual values.
.equals() cannot be used with primitives.
Important Warning (Null Safety)
String str = null;
str.equals("hello"); // ❌ NullPointerException
Safer way:
"hello".equals(str); // ✅ Safe
Real-World Rule of Thumb
Use
==for primitivesUse
.equals()for object value comparisonUse
==for objects only when you want to check if they are the same instance
Nenhum comentário:
Postar um comentário