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.
public class StringMethodDemo
public static void main(String args)
String str1 = "ABCD";
String str2 = "ABCD";
String str3 = "ABKD";
int x = str1.compareTo(str2);
int y = str1.compareTo(str3);
System.out.println("integer value when two strings "+ str1 + " and " + str2 + " are same: " + x);
System.out.println("integer value when two strings "+ str1 + " and " + str3 + " are not same: " + y);
System.out.println("integer value when two strings "+ str3 + " and " + str1 + " are not same: " + str3.compareTo(str1));
Output screenshot on compareTo() String Example
- When "ABCD" and "ABCD" are same, the method returned 0.
- When "ABCD" and "ABKD" are not same, the method returned, the difference of C and K letters ASCII value -8.
- 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).