Write a program to String comparison using Collator and String classes


This is a Java program that compares two strings using both the Collator class and the String class.

  • The Collator class is used for comparing strings based on their linguistic rules, such as language-specific character order and case sensitivity. The Locale class is used to specify the language and country of the Collator instance.
  • The compareTo method of the String class is also used to compare two strings. This method compares strings based on their Unicode values.
  • The display method is used to print out the result of the comparison. If diff is less than 0, it means that s1 comes before s2. If diff is greater than 0, it means that s1 comes after s2. If diff is equal to 0, it means that s1 and s2 are the same strings.

Source Code

import java.text.Collator;
import java.util.Locale;
public class String_Comparison
{
	public static void display(int diff, String s1, String s2) 
	{
		if (diff < 0)
		{
			System.out.println(s1 + " Comes Before " + s2);
		}
		else if (diff > 0)
		{
			System.out.println(s1 + " Comes After " + s2);
		}
		else
		{
			System.out.println(s1 + " and " + s2 + " are the Same Strings");
		}
	}
 
	public static void main(String[] args)
	{
		Locale USL = new Locale("en", "US");
 
		Collator col = Collator.getInstance(USL);
		String s1 = "Pineapple";
		String s2 = "Watermelon";
 
		int diff = col.compare(s1, s2);
 
		System.out.print("Comparing Strings using Collator : ");
		display(diff, s1, s2);
 
		System.out.print("Comparing Strings using String : ");
		diff = s1.compareTo(s2);
		display(diff, s1, s2);
	}
}

Output

Comparing Strings using Collator : Pineapple Comes Before Watermelon
Comparing Strings using String : Pineapple Comes Before Watermelon

Example Programs