how to check if one string is alphabetically before another in java code example

Example 1: how to check if a string is in alphabetical order in java

public static boolean checkAlphabetic(String input) {
    for (int i = 0; i != input.length(); ++i) {
        if (!Character.isLetter(input.charAt(i))) {
            return false;
        }
    }

    return true;
}

Example 2: java compare strings alphabetically

String a = "HYRE"; 
String b = "AGNYG";  

int compare = a.compareTo(b);  

if (compare < 0) {  
    //a is smaller
}
else if (compare > 0) {
    //a is larger 
}
else {  
    //a is equal to b
}

Tags:

Java Example