Java String compareToIgnoreCase() Method Tutorial

In this section, we will learn what the String compareToIgnoreCase() method is and how to use it in Java.

What is Java String compareToIgnoreCase() Method?

When there are two string objects and we want to compare them character by character (lexicographically) based on their Unicode numbers to see which one is bigger than the other, we can use the `compareToIgnoreCase()` method.

Notes:

  • This method is not case sensitive and so the result of comparing `Hello` with `HELLO` is the same as if we were comparing `hello` with `hello` or `HELLO` with `HELLO`.
  • If we want to compare two string objects and want to consider the case differences, we can use the compareTo () method.
  • The comparison is character by character. This means the length of each string is not the deciding factor.

For example, if we have a String object with the value `hello` and another String object with the value `o`, the second one is bigger than the first one because the Unicode of the `o` is bigger than the first character of the `hello` which is `h`.

Java compareToIgnoreCase() Method Syntax:

public int compareToIgnoreCase(String string2)

compareToIgnoreCase() Method Parameters:

The method takes one argument and that is the string value we want to compare it with the string that we’re using the method with.

compareToIgnoreCase() Method Return Value:

The return value of this method is of integer type and can be 0, positive value or negative value:

  • `0`: if the returned value was `0`, it means both string objects are equal in value.
  • `Positive value`: if the returned value was `positive`, it means the string object that we set as the argument to the method is less than the string that we’re using the method with.
  • `Negative value`: if the returned value was `negative`, it means the string object that we set as the argument of the method is bigger than the string object that we’re using the method with.

compareToIgnoreCase() Method Exceptions:

ClassCastException: If the argument value is of a type that cannot be cast to compare with this string value, then this exception will be thrown.

NullPointerException: If the argument value is null this exception will be thrown

Example: using String compareToIgnoreCase() method

public class Simple {

    public static void main(String[] args) {
        String s = "Hello";
        int o = "o".codePointAt(0);
        int h = "h".codePointAt(0);
        System.out.println("The unicode of the character `o` is: "+o);
        System.out.println("The unicode of the character `h` is: "+ h);
        System.out.println(s.compareToIgnoreCase("o"));
        System.out.println(s.compareToIgnoreCase("h"));
    }
}

Output:

The unicode of the character `o` is: 111

The unicode of the character `h` is: 104

-7

4
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies