Java String compareTo() method is used to compare two strings lexicographically. This method is declared in Comparable interface. Since String implements Comparable interface, it provides compareTo() method implementation.

Java String compareTo

Java String class has two variants of compareTo() method.

  1. compareTo(String anotherString): This compareTo method compares the String object with the String argument passed lexicographically.If String object precedes the argument passed, it returns negative integer and if String object follows the argument String passed, it returns a positive integer.It returns 0 when both the String have same value, in this case equals(String str) method will return true.

    The comparison is based on the Unicode value of each character in the strings. You should check String class source code to check how this method works.

  2. compareToIgnoreCase(String str): This compareTo method is similar to the first one, except that it ignores the case. It uses String CASE_INSENSITIVE_ORDER Comparator for case insensitive comparison.If the return value of this method is 0 then equalsIgnoreCase(String str) will return true. This method returns a negative integer, zero, or a positive integer as the specified String is greater than, equal to, or less than this String, ignoring case considerations.

Java String compareTo Example

Let’s see a small java class explaining the usage of java string compareTo methods.

The output of the above compareTo example program is shown below.


Above negative output is because “ABC” is lexicographically less than the “DEF”. The output is -3 because it compares the character values one by one. You can also confirm this with the below test program.

So when “ABC” is compared to “DEF”, the character at first index is compared. Since they are different and ‘A’ comes before ‘D’ lexicographically, it returns a negative integer with the difference between them, hence the output is -3.

So if you compare “AABC” with “ADBC”, then also you will get the same output as -3. That’s all for Java String compareTo() method example. Note that this method is not the same as the String equals() method.

Reference: Official Oracle Documentation

By admin

Leave a Reply

%d bloggers like this: