Two strings will not be considered equal if one is in the upper case and the other is in the lower case. But, you can compare two strings by ignoring the case with the help of the equalsIgnoreCase() method in Java. 

Java String equalsIgnoreCase():

Method signature:

The signature for an equalsIgnoreCase() method is as shown below.

public boolean equalsIgnoreCase(String str)

Method parameters and return type:

Return type: It returns a boolean value(true or false).

Parameters: It takes a string as a parameter.

Throws: It throws NullPointerException if the string is null.

Example 1:

Here is a simple example that explains the working of the equalsIgnoreCase() method. Here we have initialized two strings that have the same values but in different cases, but still, the equalsIgnoreCase() method will return true.

Source code:

public class Example1 {

    public static void main(String[] args) {

        String str1 = "Java tutorial";
        String str2 = "JAVA TUTORIAL";

        System.out.println(str1.equalsIgnoreCase(str2));
    }
}

Output:

run:
true
BUILD SUCCESSFUL (total time: 4 seconds)

Example 2:

In this example, we have used an array of strings containing animal names. We have also initialized a string variable with a “DOG” value. We will compare the elements of the array with the string variable using the equalsIgnoreCase() method, so we can compare without considering the case.

Source code:

public class Example2 {

    public static void main(String[] args) {

        String pet = "DOG";
        String petArray[] = {"Cat", "Rabbit", "Turtle", "Dog"};

        for (int i = 0; i < petArray.length; i++) {
            if (petArray[i].equalsIgnoreCase(pet)) {
                System.out.println("Dog is available in the array");
            }
        }
    }
}

Output:

run:
Dog is available in the array
BUILD SUCCESSFUL (total time: 1 second)

Example 3:

Here is another example of equalsIgnoreCase() method. Here we have used two arraylists. We have added lower case values in the first arraylist and upper case values in second arraylist. We will compare the values of both arraylists using equalsIgnoreCase() method.

Source code:

public class Example3 {
    
    public static void main(String[] args) {
        ArrayList list1 = new ArrayList<>(Arrays.asList("Java", "Python", "C++"));
        ArrayList list2 = new ArrayList<>(Arrays.asList("JAVA", "PYTHON", "C++"));
        
        int i=0;
        while(i<list1.size() && i<list2.size()){
            if(list1.get(i).equalsIgnoreCase(list2.get(i))){
                System.out.println("Value is same at index: "+i);
            }
            i++;
        }
    }
}

Output:

run:
Value is same at index: 0
Value is same at index: 1
Value is same at index: 2
BUILD SUCCESSFUL (total time: 1 second)

References:

Happy Learning 🙂