Write a program to compare two strings lexicographically , ignoring case differences


This Java program demonstrates how to compare two strings while ignoring the case of the characters using the compareToIgnoreCase() method of the String class.

  • The compareToIgnoreCase() method compares two strings lexicographically while ignoring the case of the characters. 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" and "java exercise" are assigned to the str1 and str2 variables, respectively. The compareToIgnoreCase() 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_IgnoringCase
{
	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.compareToIgnoreCase(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