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
1. The Trap: Using ==
to Compare Strings
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?
2. What Does ==
Actually Compare?
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.
3. Why "hello"
== "hello"
Works
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.
4. The Right Way: Use .equals()
to Compare Content
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 β