Answer
== vs .equals() in Java
This is one of the most common Java interview questions for QA/SDET roles.
== Operator — Reference Comparison
== checks if two variables point to the same memory address (same object in heap).
Java
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2); // false — different objects in heap
System.out.println(s1.equals(s2)); // true — same content
.equals() — Content Comparison
.equals() compares the actual value/content of objects.
Java
String a = "hello";
String b = "hello";
System.out.println(a == b); // true — both point to same String pool entry
System.out.println(a.equals(b)); // true — same content
String Pool Trick
Java maintains a String Constant Pool for string literals. Same literal = same object.
Java
String x = "test"; // goes to String pool
String y = "test"; // reuses same pool entry
String z = new String("test"); // creates NEW object in heap
System.out.println(x == y); // true (same pool object)
System.out.println(x == z); // false (z is in heap, not pool)
System.out.println(x.equals(z)); // true (same content)
== with Primitives vs Objects
Java
int a = 5;
int b = 5;
System.out.println(a == b); // true — primitives compare VALUE with ==
Integer x = 127;
Integer y = 127;
System.out.println(x == y); // true — Integer cache (-128 to 127)
Integer p = 200;
Integer q = 200;
System.out.println(p == q); // false — outside cache range, different objects
System.out.println(p.equals(q)); // true
In Automation Testing
Java
// ❌ Wrong — comparing String values in Selenium tests
String actualTitle = driver.getTitle();
String expectedTitle = "Login Page";
if (actualTitle == expectedTitle) { ... } // UNRELIABLE
// ✅ Correct
if (actualTitle.equals(expectedTitle)) { ... }
// or even safer (handles null)
if (expectedTitle.equals(actualTitle)) { ... }
Summary Table
| Aspect | == | .equals() |
|---|---|---|
| Compares | Memory address (reference) | Content/value |
| Works on | Primitives + Objects | Objects only |
| For Strings | Unreliable | Always use this |
| null-safe? | Yes (won't throw NPE) | Throws NPE if called on null |
