To compare two strings alphabetically in Java, you can use the compareTo
method of the String
class. This method compares the two strings lexicographically (i.e., based on the Unicode values of their characters) and returns an integer value indicating the result of the comparison.
Here is an example of how to use the compareTo
method to compare two strings alphabetically:
String str1 = "apple"; String str2 = "banana"; int result = str1.compareTo(str2); if (result < 0) { System.out.println("str1 comes before str2 alphabetically"); } else if (result > 0) { System.out.println("str2 comes before str1 alphabetically"); } else { System.out.println("str1 and str2 are equal"); }
In this example, the compareTo
method compares the strings "apple"
and "banana"
lexicographically. Because the character 'b' comes after the character 'a' in the alphabet, the method returns a positive value, indicating that str2
comes before str1
alphabetically.
You can also use the compareToIgnoreCase
method to compare two strings alphabetically, ignoring the case of the characters. This method behaves the same as compareTo
, but it converts the strings to lowercase before performing the comparison.