Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

character
digit
java
communitycreator

How to check if a character is a digit in Java

okwudili onyejiaku

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');
    }
}
Check if a character is a digit in Java

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.

RELATED TAGS

character
digit
java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring