What is the difference between == and equals() in Java?
Quick answer
== compares primitives by value and objects by reference (whether they are the exact same object), while equals() compares the logical content of two objects when the class overrides it.
For String this surprises many people: two strings with the same text created with new are different objects, so == is false even though equals() is true. String literals may be equal under == only because of the string pool, which you should never rely on.
The default equals() inherited from Object behaves like ==. If you override equals() in your own class, you must also override hashCode() so that equal objects have equal hash codes, otherwise they will be lost in a HashMap or HashSet.
String a = new String("java");
String b = new String("java");
System.out.println(a == b); // false - different objects
System.out.println(a.equals(b)); // true - same content
Integer x = 127, y = 127;
System.out.println(x == y); // true (cached small values) - do not rely on itKey points
- == compares references for objects
- equals() compares content if overridden
- Override hashCode() whenever you override equals()
Questions interviewers ask next
- What is the equals and hashCode contract?
- What is the String pool?