// importing Collator and Locale classes import java.text.Collator; import java.util.Locale; public class Main { //function to print strings (comparing & printing) public static void printString(int diff, String str1, String str2) { if (diff < 0) { System.out.println(str1 + " comes before " + str2); } else if (diff > 0) { System.out.println(str1 + " comes after " + str2); } else { System.out.println(str1 + " and " + str2 + " are the same strings."); } } public static void main(String[] args) { // Creating a Locale object for US english Locale USL = new Locale("en", "US"); // Getting collator instance for USL (Locale) Collator col = Collator.getInstance(USL); String str1 = "Apple"; String str2 = "Banana"; // comparing strings and getting the difference int diff = col.compare(str1, str2); System.out.print("Comparing strings (using Collator class): "); printString(diff, str1, str2); System.out.print("Comparing strings (using String class): "); diff = str1.compareTo(str2); printString(diff, str1, str2); } }
Output
Comparing strings (using Collator class): Apple comes before Banana Comparing strings (using String class): Apple comes before Banana
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
Java code for string comparison using Collator and String classes
Output
need an explanation for this answer? contact us directly to get an explanation for this answer