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

To check whether a given character is a number or not, Java provides a method called isDigit(). This method is a static method of the Character class and determines whether the specified character is a digit.

Syntax

Following is the syntax of the isDigit() method -

public static boolean isDigit(char ch)

Here,

  • ch ? The character to be checked.

Example

The following program uses the isDigit() method of the Character class to check whether each character in the given string "Tutorials123" is a digit or not -

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

Using ASCII value comparison

Here we have another way to check whether a character is a digit or not by comparing its ASCII value. An ASCII value stands for "American Standard Code for Information Interchange", which represents characters as numerical values. For example, the ASCII value of '0' is 48 and '9' is 57.

Example

The following is another example of checking whether a given character is a digit or not. We compare the ASCII value of the character to determine if it is a digit -

public class CharacterIsNumberOrDigitTest {
   public static void main(String[] args) {
      char ch = '7';
      if (ch >= '0' && ch <= '9') {
         System.out.println("The character '" + ch + "' is a digit.");
      } else {
         System.out.println("The character ''" + ch + "' is not a digit.");
      }
   }
}

Output

Following is the output of the above program -

The character '7' is a digit.
Updated on: 2025-05-29T17:05:50+05:30

53K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements