What is the String compareToIgnoreCase() method in Java?

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.

Syntax

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.

Return value

The compareToIgnoreCase() method returns an int such that:

  • The return value is 0 if str1 is equal to str2.
  • The return value is a positive integer if str1 is greater than str2.
  • The return value is a negative integer if str1 is less than str2.

Examples

Example 1

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);
}
}

Explanation

Two strings, str1and 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.

Example 2

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);
}
}

Explanation

  • Three strings, str1, str2, and str3, are declared in lines 3-5.
  • The 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.
  • The 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.