What is the difference between == and .equals() in Java?
Why Interviewers Ask This
Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid OOP Concepts basics — a prerequisite for any developer role.
Answer
This is a fundamental Java gotcha: == operator: compares REFERENCES — checks if two variables point to the SAME object in memory (same memory address). For primitives, compares values. String s1 = new String("hello"); String s2 = new String("hello"); System.out.println(s1 == s2); // false -- different objects in heap System.out.println(s1 == s1); // true -- same reference // Primitives: int a = 5, b = 5; System.out.println(a == b); // true -- value comparison for primitives. .equals() method: compares CONTENT — what the objects contain. Object's default equals() uses == (reference equality). You MUST override it for content equality: System.out.println(s1.equals(s2)); // true -- same content! String literal optimization: String s3 = "hello"; String s4 = "hello"; // Same object from string pool: System.out.println(s3 == s4); // true (string pool) System.out.println(s3.equals(s4)); // true. Overriding equals() correctly: public class Point { int x, y; @Override public boolean equals(Object obj) { if (this == obj) return true; // Optimization: same reference if (obj == null || getClass() != obj.getClass()) return false; Point other = (Point) obj; return this.x == other.x && this.y == other.y; } @Override public int hashCode() { // MUST override hashCode when overriding equals! return Objects.hash(x, y); } }. hashCode contract: if a.equals(b), then a.hashCode() MUST equal b.hashCode(). This ensures correct behavior in HashMap, HashSet, etc. null safety: "expected".equals(variable) instead of variable.equals("expected") — avoids NullPointerException when variable is null.
Common Mistake
Candidates often give textbook answers here. Interviewers are more impressed when you relate the concept to a specific problem you solved in a real OOP Concepts project.
Previous
What is the difference between stack and heap memory in OOP?
Next
What is a final keyword in Java?