The String compareToIgnoreCase()
method in Java is used to compare two strings lexicographically by ignoring the case of both strings. The strings are compared on the basis of the Unicode value of characters in both strings, after converting the characters to lowercase.
compareToIgnoreCase()
vs compareTo()
Both the compareToIgnoreCase()
and compareTo()
methods compare two strings lexicographically. The only difference is that unlike the compareTo()
method, the case of the strings being compared is ignored by the compareToIgnoreCase()
method.
The compareToIgnoreCase()
method is declared as shown in the code snippet below:
str1.compareToIgnoreCase(str2)
str1
: The first string to compare.str2
: The second string to compare.The compareToIgnoreCase()
method returns an int
such that:
0
if str1
is equal to str2
.str1
is greater than str2
.str1
is less than str2
.Consider the code snippet below, which demonstrates the use of the compareToIgnoreCase()
method.
class Main {public static void main( String args[] ) {String str1 = "Hello World123";String str2 = "Hello World123";int compare = str1.compareToIgnoreCase(str2);System.out.println(compare);}}
Two strings, str1
and str2
, are declared in lines 3-4. The compareToIgnoreCase()
method is used in line 6 to compare str1
and str2
. The compareToIgnoreCase()
method returns 0
, which means that str1
is equal to str2
.
Consider another example of the compareToIgnoreCase()
method, in which two unequal strings are compared.
class Main {public static void main( String args[] ) {String str1 = "Hello World123";String str2 = "Hello World122";String str3 = "Hello World1232";int compare1 = str1.compareToIgnoreCase(str2);System.out.println(compare1);int compare2 = str1.compareToIgnoreCase(str3);System.out.println(compare2);}}
str1
, str2
, and str3
, are declared in lines 3-5.compareToIgnoreCase()
method is used in line 7 to compare str1
and str2
. The compareToIgnoreCase()
method returns a positive integer 1
, which means that str1
is greater than str2
.compareToIgnoreCase()
method is used in line 10 to compare str1
and str3
. The compareToIgnoreCase()
method returns a negative integer -1
, which means that str1
is less than str3
.