Way2Java

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.

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
  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).