How to compare strings correctly
Short answer
The equals() method compares the contents of strings:
void main() {
String a = "java";
String b = new String("java");
IO.println(a.equals(b));
}Output:
trueWhy not ==
The == operator checks that both variables point to the same object in memory, not that the text is the same. Strings that come from input, files or calculations are different objects:
void main() {
String a = "java";
String b = "ja";
String c = b + "va";
IO.println(a == c);
IO.println(a.equals(c));
}Output:
false
trueIgnoring case
equalsIgnoreCase() treats upper and lower case letters as equal:
void main() {
IO.println("Yes".equalsIgnoreCase("YES"));
}Output:
trueWhen a string can be null
Calling equals() on null throws an exception. Either put the literal first or use Objects.equals():
void main() {
String input = null;
IO.println("admin".equals(input));
IO.println(Objects.equals(input, null));
}Output:
false
trueOrdering
compareTo() returns a negative number, zero or a positive number depending on which string comes first in alphabetical order:
void main() {
IO.println("apple".compareTo("banana") < 0);
IO.println("pear".compareTo("pear"));
IO.println("Zoo".compareTo("apple") < 0);
}Output:
true
0
trueUpper case letters come before lower case ones, so "Zoo" is less than "apple". For a case-insensitive comparison use compareToIgnoreCase().
Common mistake
Comparing with == sometimes "works" with literals, because Java keeps identical literals in a single object. But it breaks with a string that comes from input:
void main() {
String answer = IO.readln();
IO.println(answer == "yes");
IO.println(answer.equals("yes"));
}Output:
false
trueHere the user typed yes. Always compare text with equals().
Functions used in this recipe
- String.equals() — Compares the contents of two strings.
- String.equalsIgnoreCase() — Compares two strings ignoring letter case.
- String.compareTo() — Compares two strings in dictionary (lexicographic) order.
- Objects.equals() — Compares two objects with equals(), safely for null.