THE == VS .EQUALS( )
MISTAKE THAT WILL
RUIN YOUR CODE
If you're a Java developer, you've definitely compared objects or strings. But here’s the twist: Most bugs in beginner–intermediate Java code come from misunderstanding == and .equals(). They look similar, but silently behave very differently.
Let’s break it down with the clearest explanation and real examples.
The Core Difference
- check_circle == compares memory references (location in RAM).
- check_circle .equals() compares the content (actual values).
That’s it but the consequences are huge.
Real Life Example
Wrong way (using ==)
String a = new String("Cah kerjo");
String b = new String("Cah kerjo");
System.out.println(a == b); // false ❌
System.out.println(a.equals(b)); // true ✅a == b
“Are both variables pointing to the exact same memory spot?”
They’re not they are two different new String() objects.
a.equals(b)
“Do these two objects contain the same characters?”
Yes, both are "Hello".
Another Example: Comparing ExamCustom Objectsple
By default, your own classes inherit equals() from Object, which behaves like == (compares memory). Without overriding .equals()
class User {
String name;
User(String name) { this.name = name; }
}
User u1 = new User("Joekawai");
User u2 = new User("Joekawai");
System.out.println(u1 == u2); // false ❌
System.out.println(u1.equals(u2)); // false ❌Both are different objects → both checks return false.
Overriding .equals( ) Properly
To compare value equality, you must override equals().
class User {
String name;
User(String name) { this.name = name; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User)) return false;
User user = (User) o;
return name.equals(user.name);
}
}
User u1 = new User("Joekawai");
User u2 = new User("Joekawai");
System.out.println(u1 == u2); // false ❌
System.out.println(u1.equals(u2)); // true ✅Now .equals() checks content — the meaningful comparison.
Special Case – String Pool
Java has a String pool, so sometimes == can accidentally return true:
String x = "Sahorni";
String y = "Sahorni";
System.out.println(x == y); // true 😲 (same pooled object)But never rely on this. Use .equals() for string content every time.
When to Use == vs .equals( )
- check_circle Primitives (int, boolean, double, etc.) → Use == to compare values. .equals() is not applicable.
- check_circle Object references → == can check if two variables point to the exact same object in memory, but this is rare. .equals() does not compare memory addresses.
- check_circle Strings → Always use .equals() to compare the actual text content. Using == can lead to unexpected results due to object references.
- check_circle Custom objects → Use .equals() after overriding it to compare meaningful content. By default, == checks memory location, and the default .equals() behaves the same.
- check_circle Checking if two references point to the same object → == is the correct choice. .equals() is not intended for this purpose.