Check String Contains Only Digits in Java
Problem
A string contains only digits when every single character in it is one of 0 through 9, with nothing else mixed in.
Given a string, determine whether it consists entirely of digit characters.
Java Program
public class OnlyDigitsCheck {
public static void main(String[] args) {
String str = "12345";
boolean onlyDigits = true;
for (char c : str.toCharArray()) {
if (!Character.isDigit(c)) {
onlyDigits = false;
break; // found a non-digit, no need to keep checking
}
}
System.out.println("Contains only digits: " + onlyDigits);
}
}Output
Core Logic
Checking every character against Character.isDigit(), and stopping the instant one fails, confirms whether the whole string is made of digits.
- 1
onlyDigitsstarts astrue, assuming the string qualifies until proven otherwise. - 2A for-each loop visits each character of the string in turn.
- 3
Character.isDigit(c)checks whether the current character is one of0through9. - 4The first character that fails the check sets
onlyDigitstofalseand exits the loop immediately withbreak.
"12345", every character passes Character.isDigit(), so the loop finishes with onlyDigits still true.Key Point: This checks each character individually, rather than trying to parse the whole string as a number — a string like "007" is correctly reported as all digits, without worrying about leading zeros.
Why: Each character is checked once, and the loop exits at the first non-digit found, without allocating anything beyond a boolean flag.
Key Concepts
Approach 2: Using matches()
public class OnlyDigitsCheckRegex {
public static void main(String[] args) {
String str = "12345";
// matches() requires the pattern to cover the entire string, not just part of it
boolean onlyDigits = str.matches("[0-9]+");
System.out.println("Contains only digits: " + onlyDigits);
}
}
Output
Core Logic
A regex pattern can express 'one or more digits, and nothing else' directly, checking the whole string in a single call.
- 1
str.matches("[0-9]+")checks the pattern against the string. - 2
matches(), unlikefind()on aMatcher, requires the pattern to match the ENTIRE string, not just part of it. - 3
[0-9]+means 'one or more digit characters', so any non-digit anywhere in the string causes the whole match to fail.
"12345".matches("[0-9]+") returns true, since every character is a digit and the pattern covers the whole string.Key Point: The trailing + matters — without it, an empty string would also match [0-9]*, which is usually not the intended result for 'contains only digits'.
Why: matches() still scans every character against the pattern, but compiling and running the regex adds overhead a plain loop doesn't have.
Key Concepts
Approach 3: Java 8
public class OnlyDigitsCheckStream {
public static void main(String[] args) {
String str = "12345";
// allMatch() short-circuits at the first character that fails the check
boolean onlyDigits = str.chars().allMatch(Character::isDigit);
System.out.println("Contains only digits: " + onlyDigits);
}
}
Output
Core Logic
The same per-character check can ask a stream directly — does every character satisfy Character.isDigit()?
- 1
str.chars()returns anIntStreamof the string's character codes. - 2
.allMatch(Character::isDigit)checks that every single code passes the digit test. - 3
allMatch()returnstrueonly if every character qualifies, and stops at the first one that doesn't.
"12345", allMatch(Character::isDigit) checks all five characters and finds no non-digit, so it returns true.Key Point: allMatch() short-circuits the same way the loop's break did — it stops checking as soon as a non-digit is found.
Why: allMatch() stops as soon as it finds a non-digit, the same short-circuiting behavior as the loop's break.