Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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:

true

Why 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
true

Ignoring case

equalsIgnoreCase() treats upper and lower case letters as equal:

void main() {
    IO.println("Yes".equalsIgnoreCase("YES"));
}

Output:

true

When 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
true

Ordering

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
true

Upper 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
true

Here the user typed yes. Always compare text with equals().

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.