AI Hints
Home›Java Tutorial›Comparing Strings, Escapes and Text Blocks, String.format
Java · Lesson 22 of 120

Comparing Strings

Equals, not ==.

⏱ 2 min read▶ Video at 28:39🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Comparing strings looks simple, but there's a trap. Two equals signs don't check if the text is the same. For strings, you use a method called equals.

  • A classic trap
  • == isn't for text
  • Use equals()

equals versus ==

A and b both hold hello. But b was made by a method, at runtime. Two equals signs asks, are these the very same object, in memory? Equals asks, do they contain the same text? Equals ignore case ignores capitals. Compare to puts strings in alphabetical order, and a negative number means apple comes first. Run it. Double equals says false, even though the text is the same! Equals says true.

Main.javajava
public class Main {
    public static void main(String[] args) {
        String a = "hello";
        String b = "HELLO".toLowerCase();
        System.out.println("a is " + a + ", b is " + b);
        System.out.println("a == b      " + (a == b));
        System.out.println("a.equals(b) " + a.equals(b));
        System.out.println("ignore case " + "Java".equalsIgnoreCase("JAVA"));
        System.out.println("compareTo   " + "apple".compareTo("banana"));
        System.out.println("isEmpty     " + "".isEmpty());
    }
}
Output
a is hello, b is hello
a == b      false
a.equals(b) true
ignore case true
compareTo   -1
isEmpty     true

The rule

Always compare strings with equals. Use equals ignore case, when capitals don't matter. Use is empty, to check for an empty string. And save double equals for numbers, chars, and booleans.

keyvalue
Same text?a.equals(b)
Ignore capitalsequalsIgnoreCase
Empty?isEmpty()
==numbers, not strings

Quick check

How should you check whether a string called answer holds the text yes? Pause, and think. It's answer dot equals, yes. Double equals might work sometimes, but it isn't reliable.

Quick check
Does answer hold "yes"?

Summary

Use equals to compare the text of two strings. Double equals checks for the same object, not the same text. Next, special characters, and text blocks.

Key takeaways
  • a.equals(b)
  • not a == b
  • equalsIgnoreCase
Next up: Escapes and Text Blocks — special characters