Using compareto in java – How to Compare two Strings lexicographically in Java? | Java String compareTo() Method with Example

Using compareto in java: using compareto in java In this tutorial, we will learn how we can compare two strings lexicographically in Java. Also, know what is the method we use to compare two strings in java ie., Java String compareTo() Method. However, you may also do compare two strings by using the equals() methods in java.

Compare two Strings lexicographically in Java

Compareto string java example: Firstly, you should have some idea of what ‘lexicographically’ means? ‘lexicographically’ means ‘alphabetically ordered’ in simple words. Now, we can check the lexicographical order by comparing two strings.

The Java String Class provides many ways to compare the content of the two Strings. One way to compare the content of the two strings by using the equals() method. But today in this tutorial, we will learn how to compare two strings lexicographically in Java using the compareTo() method.

How to compare two strings without using library function?

Algorithm: 

  1. Input two strings string 1 and string 2.
  2. for (int i = 0; i < str1.length() && i < str2.length(); i ++)
    (Loop through each character of both strings comparing them until one of the string terminates):

    • If unicode value of both the characters is same then continue;
    • If unicode value of character of string 1 and unicode value of string 2 is different then return (str1[i]-str2[i])
  3. if length of string 1 is less than string2
    • return str2[str1.length()]
      else
      return str1[str2.length()]

Source Code: 

String compareto example: Let’s see the implementation of the above program here:

// Java program to Compare two strings
// lexicographically
class Compare {
  
    // This method compares two strings
    // lexicographically without using
    // library functions
    public static int stringCompare(String str1,
                                    String str2)
    {
        for (int i = 0; i < str1.length() && 
                    i < str2.length(); i++) {
            if ((int)str1.charAt(i) == 
                (int)str2.charAt(i)) {
                continue;
            } 
            else {
                return (int)str1.charAt(i) - 
                    (int)str2.charAt(i);
            }
        }
  
        // Edge case for strings like
        // String 1="Geeky" and String 2="Geekyguy"
        if (str1.length() < str2.length()) {
            return (str1.length()-str2.length());
        } 
        else if (str1.length() > str2.length()) {
            return (str1.length()-str2.length());
        }
          
        // If none of the above conditions is true,
        // it implies both the strings are equal
        else {
            return 0;
        }
    }
 // Driver function to test the above program
public static void main(String args[])
{
String string1 = new String("Geeks");
String string2 = new String("Practice");
String string3 = new String("Geeks");
String string4 = new String("BtechGeeks");

System.out.println(stringCompare(string1, string2));
System.out.println(stringCompare(string1, string3));
System.out.println(stringCompare(string2, string1));

// To show for edge case
// In these cases, the output is the difference of 
// length of the string
System.out.println(stringCompare(string1, string4));
System.out.println(stringCompare(string4, string1));
}
}

Output: 

-9
0
9
-8
8

Java String compareTo() Method

Java compareto function: Java String compareTo() method is used to compare the two strings lexicographically in Java. The comparison is based on the Unicode value of each character in the string. The String compareTo() method returns the positive number, negative number, or 0.

If the first string is greater than the second string lexicographically, then it returns a positive number. If the first string is smaller than the second string lexicographically, then it returns a negative number. If both the strings are equal lexicographically, then it returns 0.

How to Compare two Strings lexicographically

The following are the two ways to use compareTo() method in the java string class:

int compareTo(String str)

Above the comparison is between string literals. For instance,string1.compareTo(string2) where string1 and string2 are String literals.

int compareTo(Object obj)

Here the comparison is between a string and an object. For instance, string1.compareTo("Just a String object")where string1 is literal and its value is compared with the string defined in the method argument.

Do Read: 

Java program to compare two strings lexicographically using compareTo() Method

Java program to compare two strings lexicographically using compareTo() Method

class Lexicographically
{
public static void main(String args[])
{
String str1 = "Hello";
String str2 = "Hi";
String str3 = "Ram";
String str4 = "Javastudypoint";
String str5 = "Tutorial";
String str6 = "Tutorial";

//-4 because "e" is 4 times less than "i".
System.out.println(str1.compareTo(str2));

//2 because "T" is 2 times greater than "R".
System.out.println(str5.compareTo(str3));

//-2 because "H" is 2 times less than "J".
System.out.println(str1.compareTo(str4));

//-12 because "H" is 12 times less than "T".
System.out.println(str1.compareTo(str5));

//0 because both the strings are equal.
System.out.println(str5.compareTo(str6));
}
}

Output:

-4
2
-2
-12
0