Q:

String comparison using Collator and String classes in Java

belongs to collection: Java String Programs

0

String comparison using Collator and String classes in Java

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Java code for string comparison using Collator and String classes

// 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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
String concatenation with primitive data type valu... >>
<< String palindrome program in Java...