Check Character Is Digit in Java
beginner· Control Flow · Conditional Statements
Problem
A character is a digit when it falls within the range '0' to '9' — the same range-check idea used to test for letters.
Given a single character, determine whether it is a digit.
Input
'7'
Output
'7' is a digit: true
Java Program
Java
public class DigitCheck {
public static void main(String[] args) {
char ch = '7';
boolean isDigit = (ch >= '0' && ch <= '9');
System.out.println("'" + ch + "' is a digit: " + isDigit);
}
}Output
'7' is a digit: true
Core Logic
Checking whether a character falls between '0' and '9' in character code order confirms it's a digit, the same range-check technique used for letters.
How It Works
- 1
(ch >= '0' && ch <= '9')checks whetherchfalls within the digit range. - 2Because digit characters are laid out consecutively in code order, a single range check covers all ten of them.
For
ch = '7', it falls between '0' and '9', so the check confirms it's a digit.💡
Key Point: This checks the character '7', not the integer value 7 — comparing a char against another char literal never needs a cast.
Key Concepts
character range checkASCII ordering
Approach 2: Using Character.isDigit()
Java
public class DigitCheckBuiltIn {
public static void main(String[] args) {
char ch = '7';
boolean isDigit = Character.isDigit(ch);
System.out.println("'" + ch + "' is a digit: " + isDigit);
}
}
Output
'7' is a digit: true
Core Logic
Java's Character class provides a built-in digit check that also recognizes digits from non-Latin numeral systems.
How It Works
- 1
Character.isDigit(ch)reports whether the character is classified as a digit. - 2This covers Unicode digit characters beyond plain ASCII '0'-'9', unlike the manual range check.
Character.isDigit('7') returns true.💡
Key Point: For ASCII digits both approaches agree, but Character.isDigit() is the safer choice when the input could include digits from other numeral systems.
Key Concepts
Character.isDigit()wrapper class methods