Category >> Basics  

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.

Category >> Basics  
  • moisellegyg

    What about using Character.getType(ch) == Character.UPPERCASE_LETTER ?

  • Axel Howind

    That’s just bad. What about languages using non-ASCII characters like german, french, and all the others?

  • Hans Dampf

    I’d prefer to use java.lang.Character#isUpperCase() and #isLetter() instead of the magic numbers.

  • Anthony Kaser

    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.

  • ryanlr

    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;
    }

  • Ruzo

    from a string s1 create a copy s2, move to upper case s2 with toUpperCase method, so compare with s1.equals(s2)