Java String compareTo() Method Tutorial

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

What is Java String compareTo() 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 use the compareTo() method.

Notes:

  • This method is case sensitive and so the result of comparing Hello with HELLO is different than hello with hello.

Basically the Unicode number of a capital letter is different than the same letter but lowercased.

For example, the Unicode number of the letter H is 72 and the Unicode number of the letter h is 104. So the lowercased h is bigger than uppercased H.

  • If we want to compare two string objects without considering the case differences, we can use the compareToIgnoreCase() 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 h, the second one is bigger than the first one because the Unicode of the h is bigger than the first character of the Hello which is H.

Java compareTo() Method Syntax:

public int compareTo(String string2)
public int compareTo(Object object)

compareTo() Method Parameters:

The method takes one argument and that is the value we want this string value to be compared with.

compareTo() Method Return Value:

The return value of this method is of integer type and can be 0, a positive value or a 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.

compareTo() 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: compare two Strings in Java using String compareTo() method

public class Simple {

    public static void main(String[] args) {
        String s = "Hello";
        int h = "h".codePointAt(0);
        int H = "H".codePointAt(0);
        System.out.println("The unicode of the character h is: "+h);
        System.out.println("The unicode of the character H is: "+ H);
        System.out.println(s.compareTo("H"));
        System.out.println(s.compareTo("h"));
    }
}
Output: 
The unicode of the character h is: 104
The unicode of the character H is: 72
4
-32

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies