What is the difference between == and equals() in Java?
== compares references for objects (are they the same object?) and values for primitives. equals() compares content, but only if the class overrides it; the default version behaves like ==.
Explain it simply
Two printed copies of the same train ticket have the same details but are different pieces of paper. == asks "is this the very same paper?". equals() asks "do both papers say the same thing?".
String overrides equals() to compare characters. A class you write does not, until you override it, and then you must also override hashCode().
Example
String a = new String("goa");
String b = new String("goa");
System.out.println(a == b); // prints: false
System.out.println(a.equals(b)); // prints: true
int x = 5, y = 5;
System.out.println(x == y); // prints: true (primitives, by value)String literals like "goa" are pooled, so "goa" == "goa" is usually true. Do not rely on that for logic.
What to say in the interview
"For primitives, == compares values. For objects, == compares references, while equals() is meant to compare logical content. The default Object.equals is the same as ==, so I override it, along with hashCode, for value-like classes."
Common mistakes
- Comparing strings with == in conditions.
- Overriding equals without hashCode, which breaks HashMap and HashSet.