Java String compareToIgnoreCase() compares two strings lexicographically ignoring case. For case-sensitive comparisons, use the compareTo() method.
The compareToIgnoreCase() makes the comparison based on the Unicode value of each character in the strings.
1. String.compareToIgnoreCase() API
The compareToIgnoreCase() accepts only a single argument that is another string to be compared with this string.
public int compareToIgnoreCase(String str);
The comparison result is an integer value where –
- positive integer – means string object lexicographically follows the argument string.
- negative integer – means string object lexicographically precedes the argument string.
- zero – means both strings are equal.
2. Java Program to Compare Strings Ignoring Case
The following Java program compares two strings in the case-insensitive manner using the compareToIgnoreCase() method.
String name = "Alex"; Assertions.assertEquals(0, name.compareToIgnoreCase("Alex")); Assertions.assertEquals(0, name.compareToIgnoreCase("alex")); Assertions.assertEquals(0, name.compareToIgnoreCase("ALEX")); Assertions.assertEquals(-1, name.compareToIgnoreCase("alexA")); Assertions.assertEquals(1, name.compareToIgnoreCase("ale"));
3. Difference between compareToIgnoreCase() and equalsIgnoreCase()
The differences between compareToIgnoreCase() and equalsIgnoreCase() methods are:
- The compareToIgnoreCase() compares lexicographically (dictionary ordering), and equalsIgnoreCase() checks for the content of both strings. Although, both methods are case-insensitive.
- The return type of compareToIgnoreCase() is an integer type concluding that string that is greater than, less than or equal to another string. The return type of equalsIgnoreCase() is boolean, which means both strings are equal or not.
In this Java tutorial, we learned about the String.compareToIgnoreCase() API and how it lexicographically compares a given spring with another argument string. We also learned its difference with a similar-looking method equalsIgnoreCase().
Happy Learning !!
Reference: String Java Doc
Leave a Reply