You are currently viewing Why You Should Avoid == with Strings in Java

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


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

ExpressionComparesSafe to Use?
a == bMemory 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 β†’

Noel Kamphoa

Experienced software engineer with expertise in Telecom, Payroll, and Banking. Now Senior Software Engineer at Societe Generale Paris.