How-To: Java isDigit() Character function
Sometimes it is helpful to know if a character is a digit (0
-9
) or not.
The Java built-in Character class provides an isDigit()
function that determines if a character is a digit or not.
Here is an example. First, here are two character values to test:
char c1 = '9';
char c2 = 'A';
The c1
variable contains a char
value that is a digit. The c2
variable contains a char
value that is not a digit.
To invoke the isDigit()
function, use the Character
class and pass in the character as the parameter. The return value is a Boolean
(true
or false
) value.
So, to check if the c1
variable is a digit and output the result:
System.out.println( Character.isDigit(c1) ); // true
This function call returns true
, since the character '9'
is a digit. The code outputs true
. Note that the function call is inside the println()
method as its parameter.
The same process checks the c2
variable:
System.out.println( Character.isDigit(c2) ); // false
This time, the output is false
, since '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';
System.out.println( Character.isDigit(c1) ); // true
System.out.println( Character.isDigit(c2) ); // false
}
}
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.