Interview #440: Java equals() vs ==
When you start working with Java, one of the most common (and sometimes subtle) mistakes developers/testers make is misunderstanding the difference between == and .equals(). On the surface, they may seem interchangeable - but in reality, they serve very different purposes.
Disclaimer: For QA-Testing Jobs, WhatsApp us @ 91-6232667387
1. == (Reference Comparison)
👉 Think of it as:
“Are these two variables pointing to the exact same object?”
2. .equals() (Content Comparison)
👉 Think of it as:
“Do these two objects have the same value?”
🧠 Simple Example
String s1 = new String("Hello");
String s2 = new String("Hello");
System.out.println(s1 == s2); // false
System.out.println(s1.equals(s2)); // true
Why?
⚡ String Pool Special Case (Very Important)
String s1 = "Hello";
String s2 = "Hello";
System.out.println(s1 == s2); // true
Why?
👉 But don’t rely on this behavior in real logic—it can break when strings are dynamically created.
⚙️ Practical Use Cases
✅ When to use ==
1. Comparing primitives
int a = 10;
int b = 10;
System.out.println(a == b); // true
✔ Correct use case ✔ Works for int, double, char, etc.
2. Checking if two references are the same object
if (obj1 == obj2) {
// same object in memory
}
✔ Useful in performance-critical scenarios ✔ Used in singleton checks
✅ When to use .equals()
1. Comparing Strings
String name1 = "QA";
String name2 = "QA";
if (name1.equals(name2)) {
// correct way
}
✔ Always preferred for string comparison
Recommended by LinkedIn
2. Comparing Custom Objects
class User {
String name;
User(String name) {
this.name = name;
}
}
User u1 = new User("Kanchan");
User u2 = new User("Kanchan");
System.out.println(u1.equals(u2)); // false
Why false?
🔥 Fix: Override .equals()
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
User user = (User) obj;
return name.equals(user.name);
}
Now:
System.out.println(u1.equals(u2)); // true
🚨 Common Mistakes (Very Important for Interviews)
❌ Using == for String comparison
if (str1 == str2) // WRONG
👉 This may pass sometimes (due to string pool) and fail in real scenarios.
❌ Not handling null with .equals()
str1.equals(str2); // ❌ can throw NullPointerException
✅ Safer way:
"constant".equals(str1);
🧪 Real-World Automation Example (Important for You)
In Selenium / Test Automation:
String actualTitle = driver.getTitle();
String expectedTitle = "Dashboard";
if (actualTitle.equals(expectedTitle)) {
// Pass
}
Why not ==?
⚖️ Summary Table
🎯 Interview-Ready One-Liner
“== checks if two references point to the same object, while .equals() checks if two objects have the same content. For strings and objects, .equals() should be used unless you explicitly want reference comparison.”
💡 Pro Tip