The Java String compareToIgnoreCase() method compares two strings lexicographically and returns 0 if they are equal. As we know compareTo() method does the same thing, however there is a difference between these two methods. Unlike compareTo() method, the compareToIgnoreCase() method ignores the case (uppercase or lowercase) while comparing strings.
Java String compareToIgnoreCase() Method
Method Signature:
int compareToIgnoreCase(String str)
For example:
String s1 = "BEGINNERSBOOK"; //uppercase String s2 = "beginnersBOOK"; //mixedcase s1.compareTo(s2); //this would return non-zero value s1.compareToIgnoreCase(s2); //this would return zero
Similar to compareTo() method, the compareToIgnoreCase() method compares the strings based on the Unicode value of their each character. It returns 0 when the strings are equal otherwise it returns positive or negative value.
Java String compareToIgnoreCase() example
In the following example, we have three strings, all the three strings are same but their letter case is different. string1 is in uppercase, string2 is in lowercase and string3 is a mix of uppercase and lowercase letters. We are using compareToIgnoreCase()
method to compare these strings.
public class CompareExample { public static void main(String args[]) { String string1 = "HELLO"; String string2 = "hello"; String string3 = "HellO"; int var1 = string1.compareToIgnoreCase(string2); System.out.println("string1 and string2 comparison: "+var1); int var2 = string1.compareToIgnoreCase(string3); System.out.println("string1 and string3 comparison: "+var2); int var3 = string1.compareToIgnoreCase("HeLLo"); System.out.println("string1 and HeLLo comparison: "+var3); } }
Output:
string1 and string2 comparison: 0 string1 and string3 comparison: 0 string1 and HeLLo comparison: 0
Java String compareToIgnoreCase() vs compareTo() example
Lets take an example to understand the difference between these two methods. Here we are comparing two strings, which are same but their letter case is different. One of the string is in uppercase and the second string is in lowercase.
public class JavaExample { public static void main(String args[]) { //uppercase String str1 = "HELLO"; //lowercase String str2 = "hello"; System.out.println(str1.compareTo(str2)); System.out.println(str1.compareToIgnoreCase(str2)); } }
Output:
Sachin Koparde says
what if there are two different strings with different case?
Chaitanya Singh says
Obviously the method would not return 0.