Write a program to compare two strings lexicographically Two Strings


This Java program demonstrates how to compare two strings using the compareTo() method of the String class.

  • The compareTo() method compares two strings lexicographically. It returns an integer value which is zero if the strings are equal, negative if the first string is lexicographically less than the second string, and positive if the first string is lexicographically greater than the second string.
  • In this program, two strings "Java Exercise" are assigned to the str1 and str2 variables. The compareTo() method is called on str1 with str2 as an argument, and the result is stored in the res variable.
  • Then, an if-else statement is used to print a message based on the value of res. If res is less than zero, it means that str1 is lexicographically less than str2, and a message "String 1 is less than String 2" is printed. If res is equal to zero, it means that str1 is equal to str2, and a message "String 1 is equal to String 2" is printed. If res is greater than zero, it means that str1 is lexicographically greater than str2, and a message "String 1 is greater than String 2" is printed.

Source Code

public class Compare_String
{
	public static void main(String[] args)
	{
		String str1 = "Java Exercise";
		String str2 = "Java Exercise";        
		System.out.println("String 1 : " + str1);
		System.out.println("String 2 : " + str2); 
		int res = str1.compareTo(str2);
		if (res < 0)
		{
			System.out.println("String 1" +" is less than " + "String 2");
		}
		else if (res == 0)
		{
			System.out.println("String 1 "+"is equal to " +"String 2");
		}
		else
		{
			System.out.println("String 1 "+"is greater than " +"String 2 ");
		}
	}
}

Output

String 1 : Java Exercise
String 2 : Java Exercise
String 1 is equal to String 2

Example Programs