Java String compareToIgnoreCase()

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 string comes before the str argument in the dictionary order
  • returns a positive integer if string comes after 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 are equal

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

Did you find this article helpful?