Computer >> Computer tutorials >  >> Programming >> Java

Java Program to Compare two strings lexicographically


In this article, we will understand how to compare two strings lexicographically. String is a datatype that contains one or more characters and is enclosed in double quotes(“ ”). Strings are a sequence of characters. In Java programming language, strings are treated as objects.

Below is a demonstration of the same −

Suppose our input is

Input string: Morning
Input string: Evening

The desired output would be

The result of comparing the two strings is: 8

Algorithm

Step 1 - START
Step 2 - Declare two string values namely input_string_1, input_string_2.
Step 3 - Define the values.
Step 4 - Compare the two strings usinf .compareTo() function.
Step 5 - Display the result
Step 6 - Stop

Example 1

Here, we bind all the operations together under the ‘main’ function.

public class Demo {
   public static void main(String[] args) {
      String input_string_1 = "Morning";
      System.out.println("The first string is defined as: " + input_string_1);
      String input_string_2 = "Evening";
      System.out.println("The second string is defined as: " + input_string_2);
      System.out.println("\nThe result of comparing the two strings is: ");
      System.out.println(input_string_1.compareTo(input_string_2));
   }
}

Output

The first string is defined as: Morning
The second string is defined as: Evening

The result of comparing the two strings is:
8

Example 2

Here, we encapsulate the operations into functions exhibiting object-oriented programming.

public class Demo {
   static void compare(String input_string_1, String input_string_2){
      System.out.println("\nThe result of comparing the two strings is: ");
      System.out.println(input_string_1.compareTo(input_string_2));
   }
   public static void main(String[] args) {
      String input_string_1 = "Morning";
      System.out.println("The first string is defined as: " + input_string_1);
      String input_string_2 = "Evening";
      System.out.println("The second string is defined as: " + input_string_2);
      compare(input_string_1, input_string_2);
   }
}

Output

The first string is defined as: Morning
The second string is defined as: Evening

The result of comparing the two strings is:
8