How do I check if a character representing a number?

Date: 2010-09-16. Category: java.lang examples. Hits: 35K time(s).

For validation purposes we might need to check if data entered by our users is a valid data for our application to process. A simple mechanism for checking if a character inputted is a digit or not can be done by using the java.lang.Character class isDigit(char c) method.

In this example you will learn how to do this validation as can be seen in the example below. You'll create a string that contains some random alphanumeric characters. And then you'll iterate these characters, get the value at the specified location using the charAt() method. And finally check to if the character represent a digit or not.

package org.kodejava.example.lang;

public class CharacterIsDigit {
    public static void main(String[] args) {
        String str = "123ABC456def789HIJ0";

        for (int i = 0; i < str.length(); i++) {
            //
            // Determines if the specified character is a digit
            //
            if (Character.isDigit(str.charAt(i))) {
                System.out.println(str.charAt(i)
                        + " is a digit.");
            } else {
                System.out.println(str.charAt(i)
                        + " not a digit.");
            }
        }
    }
}

These are the outputs of our program:

1 is a digit.
2 is a digit.
3 is a digit.
A not a digit.
B not a digit.
C not a digit.
4 is a digit.
5 is a digit.
6 is a digit.
d not a digit.
e not a digit.
f not a digit.
7 is a digit.
8 is a digit.
9 is a digit.
H not a digit.
I not a digit.
J not a digit.
0 is a digit.