What is the difference between equals() and == in Java?
The double equals operator compares references, meaning it checks whether two variables point to the exact same object in memory. The equals method compares values, meaning it checks whether two objects are logically equal. For objects like String you almost always want equals, since two Strings with the same text can be different objects.
- The == operator compares references, checking if two variables point to the same object.
- The equals method compares values, checking if two objects are meaningfully equal.
- For objects like String, use equals to compare contents, not ==.
The core difference
Double equals asks are these the same object. The equals method asks do these objects mean the same thing. For numbers and other primitives double equals compares actual values, but for objects it compares references.
String a = new String("hi");
String b = new String("hi");
System.out.println(a == b); // false, different objects
System.out.println(a.equals(b)); // true, same text
This is a classic beginner bug. Comparing Strings with double equals sometimes seems to work because of the string pool, but you should always use equals for value comparison.
If asked about hashCode, mention the contract: if two objects are equal by equals, they must return the same hashCode. Bringing up that rule when discussing equals signals that you understand how objects behave in collections like HashMap.
Frequently asked questions
Why should you override equals and hashCode together?
Collections like HashMap use both. If two objects are equal by equals but have different hashCodes, they behave incorrectly in hash based collections.
Does == ever work for comparing strings?
It can appear to work for pooled string literals that share the same reference, but this is unreliable, so always use equals for string content.
Common follow up questions
Related interview questions
Want the full Java guide?
Read every Java concept with notes, diagrams, and code in one place. Track your progress as you go.
Open the Java guide All Java questions