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

posée 5 months ago536 vuesen

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

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

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

posée 5 months ago

1 réponse

5
✓
✓ Réponse acceptée

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.

Connectez-vous pour dire si ça a marché.

answered 5 months ago

Sign in and verify your email to post an answer.