The equalsIgnoreCase() method compares the contents of two strings regardless of their letter case and returns a boolean output. This static and built-in function from the String class in Java is useful where records are searched and matched irrespective of their case differences. Multiple different methods are provided by the java.lang package for comparing strings which we will illustrate in this post.
Read more: How to Compare Strings in Java | 14 Different Method
Quick Outline
- How to Use the Java String equalsIgnoreCase() Method?
- Possible Exception: NullPointer Exception
- Alternative of equalsIgnoreCase() Method in Java
- Conclusion
How to Use the Java String equalsIgnoreCase() Method?
The string variable can directly call the equalsIgnoreCase() method which takes another string as an argument. It retrieves a Boolean true if the contents of the two strings match and vice versa. Given below is the syntax of the equalsIgnoreCase() method in Java:
public boolean string1.equalsIgnoreCase(String string2)
Let’s explore the examples below to understand the equalsIgnoreCase() method.
Example 1: Basic Use of equalsIgnoreCase() Method
In the following example, different strings are compared using the equalsIgnoreCase() method. The string variables are declared and initialized with respective values:
String str1="JavaBeat ", str2="JavaBeat" , str3="Welcome" , str4="javaBeAT";
The equalsIgnoreCase() method compares the strings and the output is displayed:
System.out.print("String1 and String2 are same? " );
System.out.println(str1.equalsIgnoreCase(str2));
System.out.print("String1 and String3 are same? " );
System.out.println(str1.equalsIgnoreCase(str3));
System.out.print("String1 and String4 are same? " );
System.out.println(str1.equalsIgnoreCase(str4));
The following line of code demonstrates the direct calling to the equalsIgnoreCase() method. The output is returned and displayed:
System.out.print("The two strings are equal? ");
System.out.println("Beat".equalsIgnoreCase(str1));
Complete Code & Output
Example 2: Use of equalsIgnoreCase() Method With String Object
Within this example, the user inputs a string object and a string variable that are to be compared using the equalsIgnoreCase() method. For this, import the “Scanner” class from the util package to take user input:
import java.util.Scanner; // imports Scanner class
An object “strObject” of the String class is created to store the object value from the user. Similarly, a Scanner object “scan” is created to invoke the methods for reading the user input:
String strObject = new String();
Scanner scan=new Scanner(System.in);
Prompt the user to enter values for the first and second strings that will be stored in “strObject” and “str2” variables via the next() method:
System.out.println("Enter first String ");
strObject=scan.next();
System.out.println("Enter second String");
String str2=scan.next();
The strObject calls the equalsIgnoreCase() method that accepts “str2” as an argument and compares the two strings. The print statement displays the given message and the result of the method:
System.out.print("The two strings are equal? ");
System.out.println(strObject.equalsIgnoreCase(str2));
Complete Code & Output
Example 3: Use of equalsIgnoreCase() Method With String Array
The following example compares elements of a string array with a string variable via the equalsIgnoreCase() method. The string variable and array are initialized as shown in the code below:
String str="JavaBeat";
String[] strArray= {"Welcome", "to", "javabeat"};
The for loop iterates over the elements of the array by incrementing “i” in each iteration. The loop terminates when “i” exceeds the array’s length. Inside the for loop, the values of the string variable and current index are printed within the inverted commas using the special character “\”. Afterwards, the output of the method is printed:
for(int i=0; i<strArray.length; i++)
{
//displaying data in the inverted commas System.out.print("\"" + strArray[i] + "\"" + " and " + "\"" + str + "\"" + " are equal ? ");
//displaying the result of the method System.out.println( strArray[i].equalsIgnoreCase(str));
}
Complete Code & Output
Example 4: Use of String equalsIgnoreCase() Method With Empty Spaces
In Java, the null and empty spaces are not considered equal which is demonstrated in the following example. Two string variables i.e., “str1” and “str2” are initialized with the empty spaces and null value:
String str1="";
String str2=null;
A message is displayed on the console which is followed by calculating the output of the comparison of two strings via the equalsIgnoreCase() method:
System.out.print("The two strings are equal : ");
System.out.println(str1.equalsIgnoreCase(str2));
Complete Code & Output
Example 5: Use of String equalsIgnoreCase() Method With ArrayList
The ArrayList in Java is similar to an array with variable length. In this example, the elements of ArrayList are compared with a string variable. The method returns a boolean output for each element of ArrayList. For this purpose, use the following line of code to import the ArrayList:
import java.util.ArrayList; // imports Array List
An ArrayList “stringList” is declared using the ArrayList class. The add() function adds the given strings to “stringList” as shown in the code below:
ArrayList<String> stringList=new ArrayList<>();
stringList.add("Pencil");
stringList.add("books");
stringList.add("Bag");
A string variable “string2” is declared and initialized for comparing it with the ArrayList:
String string2="BoOKS";
The for loop iterates over each index of the ArrayList and matches the elements with the “string2”. Inside the for loop, the print statement displays the message and output after comparing the “string2” and the current element of ArrayList. The loop terminates when “i” exceeds the size of the ArrayList:
for(int i=0; i<stringList.size(); i++)
{ System.out.print("The strings are same? ");
System.out.println(string2.equalsIgnoreCase(stringList.get(i)) );
}
Complete Code & Output
Example 6: Use of equalsIgnoreCase() Method of StringUtils Class
The StringUtils is a utility class of the Apache Common Lang library that contains various static built-in methods for manipulating strings. In this example, we will utilize the equalsIgnoreCase() method of the StringUtils class to perform a case-insensitive comparison of two strings.
For this purpose, add the following dependency in the “pom.xml” file of the Maven project or add it in the “build.gradle” file of the Gradle project:
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
</dependencies>
After configuring the dependency within the file, include the “StringUtils” class using the following import statement:
import org.apache.commons.lang3.StringUtils;
Within the main() method, the two strings “str1” and “str2” are declared and initialized with the following values:
String str1="JavaBeat";
String str2="javabeat";
The StringUtils class invokes the equalsIgnoreCase() method that takes “str1” and “str2” as arguments and performs the comparison. The output is displayed on the console via print statement:
System.out.println("Output is : " + StringUtils.equalsIgnoreCase(str1, str2));
Complete Code & Output
Note: You can also use the compareIgnoreCase() and equalsAnyIgnoreCase() method of the StringUtils class that also serves this functionality.
Possible Exception: NullPointer Exception
A NullPointer Exception is thrown when a null string invokes the equalsIgnoreCase() method as shown in the code below:
Note: The null pointer exception does not occur if a null string is passed to the equalsIgnoreCase() method as an argument as shown in Example 4.
Alternatives of Java String equalsIgnoreCase() Method
Besides the equalsIgnoreCase() method of the String class, below is an alternative of this method that performs this exact functionality i.e., regionMatches().
Alternative: Using regionMatches()
The regionMatches() method of the String class also compares the two strings while ignoring the letter case. The only difference is that it begins the comparison of the two strings from the specified indexes. To use the regionMatches() function, the two strings “str1” and “str2” are initialized with the following values:
String str1="Welcome to JavaBeat";
String str2="JavabEAT";
Within the print statement, the “str1” invokes the regionMatches() method that accepts the following parameters:
System.out.println("Output : " + str1.regionMatches(true, 11, str2, 0, 8));
Here:
- The first argument is “true” which will perform the case-insensitive comparison of the two strings.
- The numeric value “11” marks the starting index of str1 from where the comparison should begin. It is known as “toffest”.
- Next, we will specify the other string with which the comparison is to be performed i.e., str2.
- The “0” in this line of code symbolizes the starting index of the second string. The two strings will be compared from their starting indexes to so on.
- Finally, the numeric value “8” is the last argument that denotes the total length of characters for case-insensitive comparison.
Complete Code & Output
Note: Another method of String Class “compareToIgnoreCase()” can also be used to compare the contents of two strings regardless of their letter case. However, the return type of the compareToIgnoreCase() is not boolean. Instead, it returns a numeric value as output. If the content of both the strings is equal, 0 will be returned. Similarly, a negative value is retrieved when the first string is less than the second string, and a positive value is retrieved if the first string is greater than the second string.
Conclusion
The equalsIgnoreCase() is a built-in static method of String class in Java that compares two strings while ignoring the letter case and returns a boolean output. It is directly invoked by a string variable and accepts a single string variable as discussed in this article. The return type for this function is boolean i.e., true or false. There are no specific exceptions thrown by this instance. However, a NullPointer exception occurs when the method is invoked by a null string. In this article, we have provided a practical demonstration of the Java String equalsIgnoreCase() method.