Is there an existing library method that checks if a String is all upper case or lower case in Java?

Now in StringUtils isAllUpperCase


Not a library function unfortunately, but it's fairly easy to roll your own. If efficiency is a concern, this might be faster than s.toUpperCase().equals(s) because it can bail out early.

public static boolean isUpperCase(String s)
{
    for (int i=0; i<s.length(); i++)
    {
        if (!Character.isUpperCase(s.charAt(i)))
        {
            return false;
        }
    }
    return true;
}

Edit: As other posters and commenters have noted, we need to consider the behaviour when the string contains non-letter characters: should isUpperCase("HELLO1") return true or false? The function above will return false because '1' is not an upper case character, but this is possibly not the behaviour you want. An alternative definition which would return true in this case would be:

public static boolean isUpperCase2(String s)
{
    for (int i=0; i<s.length(); i++)
    {
        if (Character.isLowerCase(s.charAt(i)))
        {
            return false;
        }
    }
    return true;
}

This if condition can get the expected result:

String input = "ANYINPUT";

if(input.equals(input.toUpperCase())
{
   // input is all upper case
}
else if (input.equals(input.toLowerCase())
{
   // input is all lower case
}
else
{
   // input is mixed case
}

Tags:

Java

String