A method to detect if string contains only uppercase letter in Java

My approach

This method loop through each character in the string, and determine if each character is in upper case. Upper case letter value is from 97 to 122.

public static boolean testAllUpperCase(String str){
		for(int i=0; i<str.length(); i++){
			char c = str.charAt(i);
			if(c >= 97 && c <= 122) {
				return false;
			}
		}
		//str.charAt(index)
		return true;
	}

Any other better approach regarding the performance?

Option 1

From Hans Dampf’s comment below:

Use java.lang.Character#isUpperCase() and #isLetter() instead of the magic numbers.

14 thoughts on “A method to detect if string contains only uppercase letter in Java”

  1. what about org.apache.commons.lang3.StringUtils.isAllUpperCase() ?

    return StringUtils.isAllUpperCase(String str);

  2. Yeah, I’ve noticed that too. But the code itself is fine, an author made an inversion of lowercase letters, so now method works fine even if there are whitespaces, punctuation or Greek alphabet 🙂

  3. String a = “eLif”;

    String b = a.toLowerCase();

    if(a.equals(b))

    System.out.println(“there is no uppercase letter in it”);

    else

    System.out.println(“there is a uppercase letter in it”);

  4. How about using Regex? It might not outperform your solution but it is easier to understand and less verbose…

    Pattern p = Pattern.compile(“[A-Z]*”);
    System.out.println(p.matcher(“ABCD”).matches()); // true
    System.out.println(p.matcher(“ABcD”).matches()); // false
    System.out.println(p.matcher(“ABC123-#!.”).matches()); // false

  5. Your example will return false if the String contains any lower case characters. It won’t return false if there are any non-alpha chars like punctuations or numbers.

    for example
    testAllUpperCase(“ABC123-#!”) will return true. None of the chars are lower case.

    If your objective is to test a string to ensure it contains ONLY upper case chars then:

    Upper case characters are actually between 65 (‘A’) and 90 (‘Z’)

    I would modify the ‘if’ statement to read
    if ( c 90) return false;
    OR
    if(c ‘Z’) return false;
    Both are functionally equivalent, but I prefer the latter as it is easier to read.

    I always view the >= and <= operators as two step operators.
    so for (c<= 'Z') you get
    1) is c less than ( ‘Z’ as this would be outside the range.

  6. Thanks. But I think the performance of your method is worse. The equals() method does the following:

    if (n == anotherString.count) {
    char v1[] = value;
    char v2[] = anotherString.value;
    int i = offset;
    int j = anotherString.offset;
    while (n– != 0) {
    if (v1[i++] != v2[j++])
    return false;
    }
    return true;
    }

Leave a Comment