English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java array

Java object-oriented (I)

Java object-oriented (II)

Java object-oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java input and output (I/O)

Java Reader/Writer

Java other topics

Usage and example of Java String compareToIgnoreCase()

Java String (String) Methods

The Java String compareTo() method compares two strings (in alphabetical order) while ignoring case.

Syntax of the compareToIgnoreCase() method of the String class:

string.compareToIgnoreCase(String str)

compareToIgnoreCase() parameter

The compareToIgnoreCase() method of the String class takes a single parameter.

  • str - String to be compared

compareToIgnoreCase() return value

  • If the strings are equal, thenReturns 0, ignoring case

  • If the string is located before the parameter str in alphabetical order, thenReturns a negative integer

  • If the string is located before the parameter str in alphabetical order, thenReturns a positive integer

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;
        //Compare str1and str2
        result = str1.compareToIgnoreCase(str2);
        System.out.println(result); // 0
        //Compare str1and str3
        result = str1.compareToIgnoreCase(str3);
        System.out.println(result); // -1
        //Compare str3and str1
        result = str3.compareToIgnoreCase(str1);
        System.out.println(result); // 1
    }
}

Here,}}

  • If case is ignored, str1and str2is equal. Therefore, str1.compareToIgnoreCase(str2) returns 0.

  • in alphabetical order, str1in str3before. Therefore, str1.compareToIgnoreCase(str3) returns a negative value, while str3.compareToIgnoreCase(str1) returns a positive value

Example2: Check if two strings are equal

class Main {
    public static void main(String[] args) {
        String str1 = "LEARN JAVA";
        String str2 = "Learn Java";
        
        //If str1and str2Equal (ignoring case differences),
        //Result is 0
        if (str1.compareToIgnoreCase(str2) == 0) {
            System.out.println("str1and str2Equal ");
        }
        else {
            System.out.println("str1and str2Not Equal ");
        }
    }
}

Output Result

str1and str2Not Equal

If string comparison needs to consider case differences, you can use

Java String (String) Methods