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

poze 5 months ago532 gadeen

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

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

Dyagnostik IA

Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.

poze 5 months ago

1 Repons

5
✓
✓ Repons yo aksepte

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.

Konekte pou di lòt moun si li te mache.

answered 5 months ago

Sign in and verify your email to post an answer.