String comparison using Collator and String classes in Java

String comparison in Java: Here, we are going to compare two strings using Collator and String Classes in Java.
Submitted by IncludeHelp, on July 12, 2019

Given two strings and we have to compare them using Collator and String classed in Java.

Using Collator class – to compare two strings, we use compare() method – it returns the difference of first dissimilar characters, it may positive value, negative value and 0.

Using String class – to compare two strings, we use compareTo() method – it returns the difference of first dissimilar characters, it may positive value, negative value and 0.

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

Code explanation:

The above code shows the use of Collator class to compare two Strings. The Collator class is similar to String class, but it is more of a general class but its methods do the same logical evaluation as String class.

It this code we have used two Strings str1 and str2 that are two be compared. Using the compareTo() method of string class we get the output "Comparing strings (using String class): Apple comes before Banana", which is same as when applied to the methods of collator class used using col object. The output when we use the compare() method of the collator class is "Comparing strings (using Collator class): Apple comes before Banana"...

Java String Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.