== vs .equals() in Java
Fast recall
Quick revision
Core answer
Whether you understand Java's object model, the String pool, and when identity and equality diverge
Saying 'always use .equals() for strings' without explaining why, or forgetting that == is correct and necessary when comparing primitives and enum constants
Explain String interning and the String pool, mention that enums are safe to compare with == because each constant is a singleton, and bring up Objects.equals() for null-safe comparisons
Interview-ready guide
Interview answer
== compares the bits in the variable — values for primitives, memory addresses for object references. .equals() compares logical content as defined by the class.
Where `==` can mislead you with objects
- String literals:
"hello" == "hello"istrueby coincidence — the JVM interns identical literals to the same pooled object;new String("hello")breaks this - Integer cache:
Integer x = 127; Integer y = 127; x == yistrue(cached); change to 128 and==returnsfalsebecause two separate objects are created - Any custom class with no overridden
equals():==and.equals()are identical — both check reference identity
Where `==` is the correct choice
- Primitives: there's no
.equals()forint,long,boolean - Enum constants: each is a JVM-guaranteed singleton;
==is null-safe and faster
Null safety
a.equals(b)throwsNullPointerExceptionifais nullObjects.equals(a, b)handles both-null and one-null cases safely — use it whenever either operand might be null
I recommend defaulting to .equals() for all object comparisons and using Objects.equals(a, b) whenever either argument might be null.
== vs .equals() in Java
Direct Answer
== compares reference identity (whether two variables point to the same object in memory). .equals() compares logical equality as defined by the class. For primitives == compares values directly because primitives are not objects.
Deep Dive & Architecture
Varargs (`Type...
args`) = syntactic sugar — compiler converts to array.
== compares reference identity (whether two variables point to the same object in memory). .equals() compares logical equality as defined by the class. For primitives == compares values directly because primitives are not objects.
Saying Java is pass-by-reference for objects because you can modify the object's fields inside a method
Common Mistakes & Pitfalls
Saying 'always use .equals() for strings' without explaining why, or forgetting that == is correct and necessary when comparing primitives and enum constants
Check your understanding
Answer these without looking back at the article.
- Is Java pass-by-value or pass-by-reference?
- Varargs in Java — Variable Arguments and Heap Pollution
- What is autoboxing and unboxing in Java? What is the Integer cache trap?
Related interview prep categories
1Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.