Java: why does `==` return false when comparing two equal strings?

asked 5 months ago534 viewsen

7
String a = scanner.nextLine(); // user types "yes"
if (a == "yes") {
    System.out.println("ok");
}

This never prints "ok" even when I type yes.

AI diagnosis

AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.

asked 5 months ago

1 Answer

5
✓
✓ Accepted answer

In Java, == on objects compares references (is it the same object in memory?), not content. The string read from input is a different object from the "yes" literal.

Use .equals():

if ("yes".equals(a)) { ... }            // null-safe order
if ("yes".equalsIgnoreCase(a.trim())) { ... }

Putting the literal first avoids a NullPointerException when a is null. == sometimes *seems* to work with literals because of string interning, which is why the bug is so confusing.

Sign in to tell others whether this worked.

answered 5 months ago

Sign in and verify your email to post an answer.