Card 05/ 09
Comparing Strings: equals, Not ==
Two strings that print the same, have the same length, and come out of == as false.
Compare the text of two strings with equals, never with ==. == asks whether two variables point at the same object, and a string read at run time is a different object from a literal in your source, even when the characters are identical.
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:
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));false
true== on two reference variables asks whether they hold the same address. typed holds the address of the pooled literal: Java keeps one shared copy of each string literal, in the string pool. 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 genuinely want to know whether two references point at the same object, make that obvious in the code, because the next reader will assume you meant equals and forgot.
← → move through sections and cards