Join our newsletter for the latest updates.

Java String compareToIgnoreCase()

The Java String compareTo() method compares two strings lexicographically (in the dictionary order), ignoring case differences.

The syntax of the string compareToIgnoreCase() method is:

string.compareToIgnoreCase(String str)

Here, string is an object of the String class.


compareToIgnoreCase() Parameters

The string compareToIgnoreCase() method takes a single parameter.

  • str - the string to be compared

compareToIgnoreCase() Return Value

  • returns 0 if the strings are equal, ignoring case considerations
  • returns a negative integer if the string comes before the str argument in the dictionary order
  • returns a positive integer if the string comes before the str argument in the dictionary order

Example: Java String compareToIgnoreCase()

class Main {
    public static void main(String[] args) {
        String str1 = "Learn Java";
        String str2 = "learn java";
        String str3 = "Learn Kolin";
        int result;

        // comparing str1 with str2
        result = str1.compareToIgnoreCase(str2);
        System.out.println(result); // 0

        // comparing str1 with str3
        result = str1.compareToIgnoreCase(str3);
        System.out.println(result); // -1

        // comparing str3 with str1
        result = str3.compareToIgnoreCase(str1);
        System.out.println(result); // 1
    }
}

Here,

  • str1 and str2 are equal if you do not consider the case differences. Hence, str1.compareToIgnoreCase(str2) returns 0.
  • str1 comes before str3 in the dictionary order. Hence, str1.compareToIgnoreCase(str3) returns negative, and str3.compareToIgnoreCase(str1) returns positive.

Example 2: Check if Two Strings are Equal

class Main {
    public static void main(String[] args) {
        String str1 = "LEARN JAVA";
        String str2 = "Learn Java";
        
        // if str1 and str2 are equal (ignoring case differences),
        // the result is 0
        if (str1.compareToIgnoreCase(str2) == 0) {
            System.out.println("str1 and str2 are equal");
        }
        else {
            System.out.println("str1 and str2 are not equal");
        }
    }
}

Output

str1 and str2 not equal

If you need to compare two strings with case differences taken into consideration, use either