Why You Should Avoid `==` with Strings in Java
Introduction
String comparison in Java can be confusing for beginners — especially when using ==. While your code may compile, it might not behave as expected.
In this tutorial, you'll learn how string comparison in Java actually works, why == fails in many cases, and the correct way to use .equals() safely — including a trick to avoid NullPointerException.
📚 Related: Understanding Java Strings – Immutable and Powerful
==
to Compare Strings
1. The Trap: Using Let’s look at this simple example:
String a = "hello";
String b = "hello";
System.out.println(a == b); // true
Seems correct, right? But try this:
String a = new String("hello");
String b = new String("hello");
System.out.println(a == b); // false
What just happened?
==
Actually Compare?
2. What Does In Java, the ==
operator does not compare string content. It checks if two variables reference the exact same object in memory.
So even if two strings contain identical characters, ==
may return false
if they’re not the same object.
"hello"
== "hello"
Works
3. Why When you write:
String a = "hello";
String b = "hello";
Both a
and b
point to the same object in the String pool — a special memory area for string literals. Java reuses these constants to save memory.
But when you write:
String a = new String("hello");
You create a new String object in the heap, even if the value already exists in the pool.
That's why:
"hello" == new String("hello") // false
Use .equals()
instead.
.equals()
to Compare Content
4. The Right Way: Use To compare actual characters inside a string, use:
String a = new String("hello");
String b = new String("hello");
System.out.println(a.equals(b)); // true
5. Bonus Tip: Null-Safe Comparison
Avoid this mistake:
if (input.equals("yes")) {
// ❌ Risky if input is null
}
This can throw a NullPointerException
if input
hasn’t been initialized. It's a common oversight among Java beginners.
📚 Read more about what causes NullPointerExceptions and how to avoid them
Do this instead:
if ("yes".equals(input)) { ... } // ✅ Safe even if input is null
Summary
Expression | Compares | Safe to Use? |
---|---|---|
a == b |
Memory reference | ❌ No |
a.equals(b) |
Content/value | ✅ Yes |
"const".equals(b) |
Content, null-safe | ✅ Yes |
Conclusion
Using ==
to compare strings might work by accident — but it’s unreliable and risky. Always use .equals()
to compare string values, and learn how string interning works to understand why some comparisons seem to work.
You can find the complete code of this article here in GitHub.
Want to dive deeper? Explore how Java Strings work under the hood →
Originally published on my blog: https://nkamphoa.com/string-comparison-in-java/