== for Primitives vs Objects in Java
Fast recall
Quick revision
Core answer
== compares the primitive values after any required numeric promotion. With two reference operands, it checks whether both references are null or denote the same object. For example, two separate String objects can contain "hello" yet be unequal by ==.Understanding of Java's value vs reference semantics — the foundational distinction that affects every data structure decision
Using == to compare String or Integer values and being confused when identical-looking values return false
Mention the Integer cache (-128 to 127) as a gotcha where == sometimes works for objects, making the bug even harder to spot
Interview-ready guide
Interview answer
For primitives, == compares values. For example, int a = 5; long b = 5L; makes a == b true after Java promotes the int for the numeric comparison. It does not compare where a primitive is stored.
For references, == asks an identity question: do these references denote the same object, or are both null? If String first = new String("hello") and String second = new String("hello"), then first == second is false because they are separate objects. first.equals(second) is true because String defines equality by character content.
So I choose the comparison from the operand type and the question being asked. I use == for primitive values and when reference identity is intentional. I use a class's equality method for logical value comparison, while remembering that a class which does not override Object.equals() still has identity-based equality.
== for Primitives vs Objects in Java
Direct Answer
With two primitive operands, == compares the primitive values after any required numeric promotion. With two reference operands, it checks whether both references are null or denote the same object. For example, two separate String objects can contain "hello" yet be unequal by ==.
Common Mistakes & Pitfalls
- String comparison with
==:if (userName == "admin")sometimes works (string interning) but breaks when the string comes from user input or a file — an intermittent bug. - Ignoring the Integer cache:
Integer x = 100; Integer y = 100; x == yistrue, but at200it'sfalse.==seems to work forIntegeruntil values exceed 127. - Confusing equals() direction:
userName.equals("admin")throwsNullPointerExceptionifuserNameis null; use"admin".equals(userName)orObjects.equals(...).
Check your understanding
Answer these without looking back at the article.
- What is the Integer cache in Java?
- Will Integer i1 = 127; Integer i2 = 127; i1 == i2 be true?
- What happens if you call .equals() on a null reference?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.