The Java String.equalsIgnoreCase() compares the current string with the specified string in a case-insensitive manner. Using equalsIgnoreCase(), two strings are considered equal if they are of the same length and corresponding characters in the two strings are equal, ignoring their cases.
A similar method String.equals() compares the strings in a case-sensitive manner.
Never use
'=='
operator for checking the strings equality. It checks the object references, which is not desirable in most cases.
1. String.equalsIgnoreCase() API
The syntax to use the equalsIgnoreCase() API is as follows:
boolean isEqual = thisString.equalsIgnoreCase( anotherString );
Note that if we pass null as the method argument, the comparison result will be false.
2. String.equalsIgnoreCase() Example
The following Java program demos a few comparisons using the equalsIgnoreCase() API. We can see that passing null returns false. Also, equalsIgnoreCase() returns false when the strings have different content.
Assertions.assertFalse("null".equalsIgnoreCase(null));
Assertions.assertFalse("abc".equalsIgnoreCase("abcd")); //Different strings
Assertions.assertTrue("abc".equalsIgnoreCase("ABC"));
Assertions.assertTrue("ABC".equalsIgnoreCase("AbC"));
3. Difference between equals() and equalsIgnoreCase()
Clearly, the primary difference between equals() and equalsIgnoreCase() APIs is their case sensitivity while performing the comparisons.
- equals() method makes the case-sensitive comparison.
- equalsIgnoreCase() method makes the case-insensitive comparison.
Happy Learning !!
Reference: String Java Doc