How to check if a String is all upper case or lower case in Java?

How to check if a String is all upper case or lower case in Java?

In Java, you can check if a string is all upper case or lower case by iterating through each character of the string and using the Character.isUpperCase() and Character.isLowerCase() methods. Here are simple methods to do this:

Check if All Upper Case

public static boolean isAllUpperCase(String str) { if (str == null || str.isEmpty()) { return false; } for (char c : str.toCharArray()) { if (Character.isLetter(c) && !Character.isUpperCase(c)) { return false; } } return true; } 

Check if All Lower Case

public static boolean isAllLowerCase(String str) { if (str == null || str.isEmpty()) { return false; } for (char c : str.toCharArray()) { if (Character.isLetter(c) && !Character.isLowerCase(c)) { return false; } } return true; } 

Usage

String myString = "HELLO"; boolean isUpperCase = isAllUpperCase(myString); // returns true boolean isLowerCase = isAllLowerCase(myString); // returns false 

Notes

  • These methods consider only alphabetic characters (isLetter). Non-alphabetic characters (like digits or punctuation) are ignored. If you want to include these in your checks, you would need to modify the logic accordingly.
  • An empty string or null will return false for both methods. You might want to change this behavior based on your specific requirements.

More Tags

twitter file-get-contents fluent-assertions median pdf-form nuxt.js android-paging-library motion-detection dynamics-crm-2016 google-compute-engine

More Java Questions

More Cat Calculators

More Fitness Calculators

More Gardening and crops Calculators

More Financial Calculators