How to compare strings using the compareTo() method in Java

The Java compareTo() method compares the given string lexicographically (an order similar to the one used in a dictionary) with the current string on the basis of the Unicode value of each character in the strings. This method returns an integer upon its implementation.

The Java lexicographic order is as follows:

  1. Numbers
  2. Uppercase
  3. Lowercase

There are three cases when the compareTo() method is used.

Case 1: Both strings are lexicographically equivalent

The method returns 00 if the two strings are equivalent:

class MyClass {
public static void main( String args[] ) {
String str1="abcd";
String str2="abcd";
System.out.println(str1.compareTo(str2));
}
}
1 of 5

Case 2: String calling method is lexicographically first

The method returns a negative number when the string calling the method lexicographically comes first:

class MyClass {
public static void main( String args[] ) {
String str1="abCd";
String str2="abcd";
System.out.println(str1.compareTo(str2));
}
}
1 of 3

Case 3: Parameter passed in the method comes lexicographically first

The method returns a positive number when the parameter passed in the method lexicographically comes first:

class MyClass {
public static void main( String args[] ) {
String str1="abcd";
String str2="abCd";
System.out.println(str1.compareTo(str2));
}
}
1 of 3

This number represents the difference between the Unicode values of the string passed as the input parameter (str2) and the string (str1) calling the method.

result= Unicode of str1 - Unicode of str2

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved