compareTo() String Example

compareTo() String Example

java.lang.String class comes with many methods to check two strings contain same characters in the same sequence. To do this, String class comes with equals(), compareTo(), equalsIgnoreCase() and compareToIgnoreCase() methods. This tutorial is on compareTo() String.
Now we discuss compareTo() String method.

Following is the method signature as defined in String class.

  • public int compareTo(String anotherString): Compares two strings lexicographically. Character by character, of both strings, is compared. If the ASCII values of both characters is same, then the method returns 0 else some integer value of the difference of ASCII values. Note, equals() method returns boolean value.

Following example on compareTo() String illustrates the usage of the above method.


compareTo() String
Output screenshot on compareTo() String Example

  1. When "ABCD" and "ABCD" are same, the method returned 0.
  2. When "ABCD" and "ABKD" are not same, the method returned, the difference of C and K letters ASCII value -8.
  3. When "ABKD" and "ABCD" are not same, the method returned, the difference of K and C letters ASCII value 8.

A similar method exists which compares case-insensitive comparison – compareToIgnoreCase().

Another similar method exists to compare two characters: Java Character compareTo(Character c1) Example

What is lexicographical comparison?

Character by character of each string is compared. That is, the method takes characters, one-by-one, of both strings and compares. When both characters are same, the method returns 0 (the difference of their ASCII values). When dissimilar characters are compared and thereby when the difference is non-zero, further comparison is stopped and the difference is returned. This is known as lexicographical comparison (character-by-character comparison).

Leave a Reply

Your email address will not be published. Required fields are marked *