DEV Community

Edwin Torres
Edwin Torres

Posted on • Edited on

5 2

How-To: Java isDigit() function

Sometimes it is helpful to know if a character is a digit (0-9) or not.

The built-in Java Character class provides an isDigit() function that determines if a character is a digit or not. If it is, the function returns true. Otherwise, it returns false.

Here is an example. Declare and populate some character values to test:

char c1 = '9';
char c2 = 'A';
Enter fullscreen mode Exit fullscreen mode

The c1 variable contains a character value that is a digit. The c2 variable contains a character value that is not a digit.

To invoke the isDigit() function, use the Character class and pass in the character to test as the parameter. The return value of the function is a Boolean (true or false) value.

This statement checks if the c1 variable contains a digit and stores the result in a Boolean variable b1:

boolean b1 = Character.isDigit(c1);
Enter fullscreen mode Exit fullscreen mode

Since the character '9' is a digit, the statement assigns true to b1.

The same process checks the c2 variable:

b1 = Character.isDigit(c2);
Enter fullscreen mode Exit fullscreen mode

This time, the program assigns false to b1, because 'A' is not a digit.

Here is the complete program:

public class Example {
  public static void main(String[] args) throws Exception {

    char c1 = '9';
    char c2 = 'A';

    boolean b1 = Character.isDigit(c1);
    System.out.println(b1); // true

    b1 = Character.isDigit(c2);
    System.out.println(b1); // false
  }
}
Enter fullscreen mode Exit fullscreen mode

The Character.isDigit() function is very useful when determining if a character is a digit or not. This can help with a variety of string processing tasks in the programs you write.

Thanks for reading. 😃

Follow me on Twitter @realEdwinTorres for more programming tips and help.

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.