How to check if a given character is a number/letter in Java?


The Character class is a subclass of Object class and it wraps a value of the primitive type char in an object. An object of type Character contains a single field whose type is char. We can check whether the given character in a string is a number/letter by using isDigit() method of Character class. The isDigit() method is a static method and determines if the specified character is a digit.

Example

public class CharacterIsNumberOrDigitTest {
   public static void main(String[] args) {
      String str = "Tutorials123";
      for(int i=0; i < str.length(); i++) {
         Boolean flag = Character.isDigit(str.charAt(i));
         if(flag) {
            System.out.println("'"+ str.charAt(i)+"' is a number");
         } else {
            System.out.println("'"+ str.charAt(i)+"' is a letter");
         }
      }
   }
}

Output

'T' is a letter
'u' is a letter
't' is a letter
'o' is a letter
'r' is a letter
'i' is a letter
'a' is a letter
'l' is a letter
's' is a letter
'1' is a number
'2' is a number
'3' is a number

Updated on: 23-Nov-2023

39K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements