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';
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);
Since the character '9'
is a digit, the statement assigns true
to b1
.
The same process checks the c2
variable:
b1 = Character.isDigit(c2);
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
}
}
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)