Java String equalsIgnoreCase() method

The equalsIgnoreCase() method in Java is used to compare two strings ignoring case differences. It checks whether two strings are equal, disregarding whether the characters are uppercase or lowercase.

Syntax:


public boolean equalsIgnoreCase(String anotherString)

Parameters: anotherString: The string to compare with the current string.

Return Value:

  1. The method returns true if the two strings are equal ignoring case, i.e., they have the same sequence of characters, but the case of those characters does not matter.
  2. It returns false if the strings are not equal (ignoring case).

Example 1: Case-Insensitive Comparison


public class EqualsIgnoreCaseExample1 {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "hello";
        
        // Comparing two strings ignoring case
        if (str1.equalsIgnoreCase(str2)) {
            System.out.println("The strings are equal (case ignored).");
        } else {
            System.out.println("The strings are not equal.");
        }
    }
}

Output: The strings are equal (case ignored).

Explanation: In this example, str1.equalsIgnoreCase(str2) returns true because both strings contain the same characters, and the case is ignored during the comparison.

Example 2:


public class EqualsIgnoreCaseExample2 {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "hEllo";
        
        // Comparing two strings ignoring case
        if (str1.equalsIgnoreCase(str2)) {
            System.out.println("The strings are equal (case ignored).");
        } else {
            System.out.println("The strings are not equal.");
        }
    }
}

Output: The strings are equal (case ignored).

Example 3: Comparing a String with null


public class EqualsIgnoreCaseExample3 {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = null;
        
        // Comparing a string with null
        if (str1.equalsIgnoreCase(str2)) {
            System.out.println("The strings are equal.");
        } else {
            System.out.println("The strings are not equal.");
        }
    }
}

Output: The strings are not equal.

Explanation: The equalsIgnoreCase() method returns false when one of the strings is null. It does not throw a NullPointerException, but simply returns false.