How to check if a Char is uppercase in Java?

In this quick post, we will provide a Java program using which you can check if a character is an uppercase character in Java or not. To do this, we will use Apache Commons Lang library, and you need to have a copy of the following JAR file in your classpath=> commons-lang3-3.1.jar.


Java Program – Check if Character is UpperCase


We will use the method isAsciiAlphaUpper, defined in org.apache.commons.lang3.CharUtils to identify if the character is an uppercase character in Java or not. The complete Java program is provided below:[ File name: checkUpperCase.java ]. Note that this method returns a boolean which is set to True if the input character is an uppercase one. It returns false otherwise. You can get the output in a boolean variable and handle it separately in your code, if required.

import org.apache.commons.lang3.CharUtils;
public class checkUpperCase {
  public static void main(String[] args) throws Exception {
    System.out.println("Check if a character is uppercase in Java");
    //Test - 1
    char myChar='a';
    //Print true if upper case, false otherwise
    System.out.println("Is "+myChar+" Uppercase? "+ CharUtils.isAsciiAlphaUpper(myChar));
    //Test -2
    myChar='A';
    System.out.println("Is "+myChar+" Uppercase? "+ CharUtils.isAsciiAlphaUpper(myChar));
    //Test-3
    myChar='2';
    System.out.println("Is "+myChar+" Uppercase? "+ CharUtils.isAsciiAlphaUpper(myChar));
   
  }
}

Example Output


The program provided above produces the following output, depending on the input we gave:

javac -classpath .;commons-lang3-3.1.jar checkUpperCase.java

java -classpath .;commons-lang3-3.1.jar checkUpperCase

Check if a character is uppercase in Java
Is a Uppercase? false
Is A Uppercase? true
Is 2 Uppercase? false

Apache CharUtils



CharUtils greatly simplifies all your basic coding requirements, and it is just a line of code here to check if a character is an uppercase character or not. You can test this example with your own input, and post a comment if you are stuck.

No comments: