How to check if a character is a digit in Java

Overview

We can check if a character is a digit in Java without using any built-in method. A digit character is any numeric character from 0 and 9. The way to achieve this is by using an if-else condition.

Syntax

if(character <= '0' && character >= '9'){
// character is digit
}else{
// character is not digit
}
Check if a character is a digit in Java

Parameter

character: This is the character that we're checking to see if it is a digit or not.

Code example

class HelloWorld {
// create function to check if digt
static void checkIfDigit(char character){
if (character >= '0' & character <= '9'){
System.out.println(character +" is digit");
}else{
System.out.println(character +" is not digit");
}
}
public static void main( String args[] ) {
// check if some characters are digits
checkIfDigit('e');
checkIfDigit('1');
checkIfDigit('3');
checkIfDigit('%');
checkIfDigit('4');
}
}

Explanation

In the code above:

  • Line 3: We create a function to check if a character is a digit character. It takes a character as a parameter and applies the above condition.
  • Lines 12–16: With the function we created, we check several characters to see if they are digits and print the results to the console.

Free Resources