Help me understand the difference between == and .equals() in Java
If you're new to Java, this one will bite you eventually. Might as well understand it now.
Look at this:
String a = new String("hello");
String b = new String("hello");
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
Wait — both are "hello." Why does == say false?
Because == checks if two variables point to the same object in memory. It doesn't care about the content. It's asking "are these literally the same box?"
.equals() checks if the values inside are the same. It's asking "do these boxes contain the same thing?"
So when you wrote new String("hello") twice, Java created two separate objects. Same content, different boxes. That's why == returns false.
Where it gets tricky:
String x = "hello";
String y = "hello";
System.out.println(x == y); // true
This one returns true because Java reuses string literals from something called the String Pool. Since both point to the same pooled object, == says true. But you should never rely on this. It's an optimization, not a guarantee.
The simple rule:
Comparing objects? Use .equals().
Comparing primitives like int, char, boolean? Use ==.
That's it. Get this right and you'll avoid one of the most common bugs in beginner Java code.
Got questions? Drop them below.
Posted May 8, 2026, 3:45 PM UTC