How do I compare strings in Java?

I’ve been using the == operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into .equals() instead, and it fixed the bug.

Is == bad? When should it and should it not be used? What’s the difference?

Great question — and an important one for understanding how Java (or other object-oriented languages like C#) handles comparisons, especially with strings.


== vs .equals() in Java

Expression Compares Result
== References (memory) true if both point to the same object
.equals() Contents (value) true if both have the same data

Example:

String a = new String("hello");
String b = new String("hello");

System.out.println(a == b);        // false (different objects)
System.out.println(a.equals(b));   // true (same contents)

Even though both strings say "hello", a and b are two separate objects, so == returns false.


When to Use:

Use == when:

  • You want to check if two references point to the exact same object.
  • Example: checking if a singleton instance is reused.

Use .equals() when:

  • You want to compare string values, or object data.
  • Most of the time with strings, .equals() is the correct choice.

Common Pitfall:

If you write:

String s = "hello";
if (s == "hello") {
    // might return true — because of string interning
}

This might work due to Java’s string pool, but it’s unreliable and breaks if the string is constructed dynamically:

String s = new String("hello");
if (s == "hello") {
    // false — different object
}

Best Practice:

Always use .equals() when comparing string content or any object that overrides .equals().

And to avoid a NullPointerException, use:

"constant".equals(someVariable)

instead of:

someVariable.equals("constant") // might throw if someVariable is null