Card 05/ 09

GotchaDifficulty: Intermediate1 min

Why == Says Two Identical Strings Are Different

A comparison that passes every test and fails in production. The two strings print the same, have the same length, and come out of == as false.

java
String typed = "ACTIVE";
String fromInput = new Scanner(System.in).nextLine();   // the user types ACTIVE

System.out.println(typed == fromInput);
System.out.println(typed.equals(fromInput));
text
false
true

== on two reference variables asks whether they hold the same address. typed holds the address of the pooled literal. fromInput holds the address of a string built at runtime out of bytes that arrived from somewhere. Two objects, identical contents, different addresses.

Use .equals for every string comparison, without exception. Put the value you know is not null on the left — "ACTIVE".equals(status) cannot throw, while status.equals("ACTIVE") can.

There is no case where == is the better choice for text. If you want to know whether two references point at the same object, say so with a comment, because the next reader will assume you meant equals and forgot.