CodeBlanks Logo Icon CodeBlanks

equals and equalsIgnoreCase

Learn string comparison with equals().

equals and equalsIgnoreCase

To compare the content of two Strings use equals. The == operator compares references, so for Strings equals is preferred.

String a = "Hello";
String b = "Hello";
System.out.println(a.equals(b));         // true
System.out.println(a.equalsIgnoreCase(b)); // true (case insensitive)

equalsIgnoreCase ignores case differences. "JAVA".equalsIgnoreCase("java") returns true.

The most common mistake in String comparison is using ==.

Practice Compare with equals

Write a Main class with a main method. Assign "Hello" to String a and "hello" to String b. Print a.equals(b) and a.equalsIgnoreCase(b) with println.

Sample solution

Main.java
public class Main {
    public static void main(String[] args) {
        String a = "Hello";
        String b = "hello";
        System.out.println(a.equals(b));
        System.out.println(a.equalsIgnoreCase(b));
    }
}

Expected output

false
true

Why does == not work?

Strings are reference types. == checks whether two variables point to the same object, not whether their content matches.

String a = "Hello";
String b = new String("Hello");
System.out.println(a == b);       // false!
System.out.println(a.equals(b)); // true

Java pools (interns) some Strings, so == may sometimes return true. But this is not reliable; always use equals.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the methods

Term Meaning
equals Content equal
equalsIgnoreCase Case insensitive
== Reference compare
!= Not equal

2 What does "JAVA".equalsIgnoreCase("java") return?

  • false
  • true Correct answer
  • null
  • Error

Explanation: equalsIgnoreCase ignores case differences.

3 Complete the equals call

Question
boolean same = a.____(b);
Answer
boolean same = a.equals(b);

Explanation: a.equals(b) compares the content of two strings.

All lessons in Beginner