Comparing strings by their alphabetical order

To compare strings by their alphabetical order in Java, you can use the compareTo() method of the String class.

The compareTo() method compares two strings lexicographically, which means that it compares the strings character by character, according to the Unicode value of each character. If the strings are equal, the method returns 0. If the first string is lexicographically greater than the second string, the method returns a positive integer. If the first string is lexicographically less than the second string, the method returns a negative integer.

Here is an example of how to use the compareTo() method to compare two strings:

String str1 = "apple";
String str2 = "banana";

int result = str1.compareTo(str2);
if (result < 0) {
    System.out.println(str1 + " comes before " + str2);
} else if (result > 0) {
    System.out.println(str1 + " comes after " + str2);
} else {
    System.out.println(str1 + " is equal to " + str2);
}

In this example, the output will be "apple comes before banana", because "a" comes before "b" in the alphabet.

I hope this helps. Let me know if you have any questions.