Java String equalsIgnoreCase() Method

In Java programming, comparing strings is a crucial task, and the equals() method plays a central role in this process. However, there are situations where we need to perform case-insensitive string comparisons. This is where the equalsIgnoreCase() method, an inherent feature of the String class, becomes essential.

This article explores the need, advantages, and usage syntax of equalsIgnoreCase(), providing practical insights through code snippets. Engaging with these examples will enhance your understanding and readiness to apply this method effectively in real-world coding challenges.

What is the equalsIgnoreCase() method in Java?

The Java equalsIgnoreCase() method compares two strings while disregarding any differences in the case of the letter. It evaluates whether the specified string is equal to another string. The function returns true if they match and false if they do not. This functionality is encapsulated within the String class of the java.lang package.

In Java, the equalsIgnoreCase() method enables the comparison of two strings without considering their case (either lower or upper). The method outputs a boolean value, indicating true if the provided argument is not null and represents an equivalent string, irrespective of case; otherwise, it returns false.

What is the difference between equals() and equalsIgnoreCase()?

It is quite obvious, isn’t it? As the name suggests, the method equalsIgnoreCase() ignores the case (case insensitive) while the equals() method considers the case of the string. The equals() method conducts a meticulous character-by-character comparison between two strings. It ensures that each character in one string exactly matches the corresponding character in the other.

In contrast, the equals method is case-sensitive, strictly considering the case of each character. Conversely, the equalsIgnoreCase method offers a case-insensitive approach, allowing for comparing values while disregarding variations in letter case, making it particularly useful when case distinctions are irrelevant.

What is the Syntax of the equalsIgnoreCase() method in Java?

Before we take a look at some examples of codes that involve the equalsIgnoreCase() method, let us take a look at the syntax of it:

string1.equalsIgnoreCase(string2)

The described syntax evaluates whether string2 is identical to string1, returning False if there is a match and True otherwise. The equalsIgnoreCase() method in Java takes a single String parameter.

This method returns a boolean value: True if the corresponding characters of both strings are equal, disregarding case differences, and False if the strings are not equal.

Now that we know the theory of the equalsIgnoreCase() method of the String class in Java let us implement this knowledge and see some applications of it.

class Main 
{
    public static void main(String[] args) 
    {
        String str1 = "FirstCode";
        String str2 = "FirstCode";
        String str3 = "fIRSTCodE";
        Boolean result;
        System.out.println(str1.equalsIgnoreCase(str2)); 
        System.out.println(str1.equalsIgnoreCase(str3)); 
        System.out.println(str3.equalsIgnoreCase(str1)); 
    }
}

Output:

True
True
True

The above code uses the equalsIgnoreCase() method for case-insensitive string comparison. Three string variables (str1, str2, and str3) are initialized with different cases but the same content.

The equalsIgnoreCase() method is then employed to compare pairs of these strings, and the results are printed. The method correctly returns true in each comparison as it ignores case differences, confirming that the strings “FirstCode” in various cases are considered equal.

Internal working of the equalsIgnoreCase() method

Since we know how the equalIgnoreCase() method works, let us delve deeper into its working at look at what happens behind the scenes:

public boolean equalsIgnoreCase(String str1) 
{    
       return (this == str1) ? true    
               : (str1 != null)    
               && (str1.value.length == value.length)    
               && regionMatches(true, 0, str1, 0, value.length);    
   }

Let us understand the above code better. The equalsIgnoreCase() method in Java’s String class first checks if the provided string (str1) is the same reference as the calling object (this). It returns true if they are the same reference, indicating that the strings are equal. If the references differ, it further checks if “str1” is not null and has the same length as the calling string (value.length).

Finally, it employs the regionMatches method with a case-insensitive flag to compare the substrings of both strings from the start index (0) up to the length of the calling string. The method returns true if these conditions are met, signifying a case-insensitive equality. Otherwise, it returns false.

You may ask, “What is regionMatches() now?” well, it is essentially an inbuilt method that checks the similarity of strings. This method accepts 5 arguments, as shown below:

regionMatches(boolean ignoreCase, int toffset, String str1, int offset, int len)

When set to true, the “ignoreCase” parameter instructs the method to perform case-insensitive character comparison. The “toffset” parameter denotes the starting offset within the calling string where the subregion begins. The “str1” parameter is the string argument against which the comparison is made.

The “offset” parameter indicates the starting offset of the subregion in the provided string (str1). Finally, the “len” parameter specifies the number of characters to be compared between the two substrings. By incorporating these parameters, the method offers a means of comparing specific regions within strings, with the option to ignore case differences based on the ignoreCase flag.

Using equalsIgnoreCase() to compare a string with array list elements

import java.lang.String;
import java.util.ArrayList;  
public class Main
{  
    public static void main(String[] args) 
    {  
        String str1 = "FirstCode";  
        ArrayList<String> fruits = new ArrayList<>();  
        fruits.add("JAVA");   
        fruits.add("PyThoN");  
        fruits.add("FIRstcoDE");  
        for (String str : fruits) 
        {  
            if (str.equalsIgnoreCase(str1)) 
            {  
            	System.out.println("String is present in the list");  
            }  
        }    
    }  
}

Output:

String is present in the list

This code shown above initializes a string (str1) with the value “FirstCode” and an ArrayList of strings (fruits). The ArrayList contains three elements: “JAVA,” “PyThoN,” and “FIRstcoDE.” The code then iterates through the elements in the ArrayList using a for-each loop. For each element, it checks if the string, when compared using equalsIgnoreCase() with the value of str1, results in a match.

If a match is found, it prints “String is present in the list.” In this example, the third element of the ArrayList, “FIRstcoDE,” satisfies the case-insensitive comparison condition, triggering the print statement. This code illustrates the practical use of the equalsIgnoreCase() method for comparing strings case-insensitively, applied within a loop for elements in an ArrayList.

Conclusion

In summary, the article provides an overview of Java’s equalsIgnoreCase() method, as we highlight its importance for case-insensitive string comparisons. Through clear explanations and practical examples, you have learned this method’s syntax, internal workings, and real-world applications. The equalsIgnoreCase(), Java developers can improve their ability to perform precise string comparisons, contributing to the reliability of their code.

Leave a Reply

Your email address will not be published. Required fields are marked *