Count Digits in a String in Java
Problem
A digit is any of the characters 0 through 9 that can appear inside a string alongside letters and symbols.
Given a string, count how many digits it contains.
Java Program
public class CountDigits {
public static void main(String[] args) {
String str = "Order66Confirmed42";
int count = 0;
for (char c : str.toCharArray()) {
if (Character.isDigit(c)) count++; // counts 0-9 only
}
System.out.println("Digits: " + count);
}
}Output
Core Logic
A single pass through the string, checking each character with Character.isDigit(), is enough to tally every digit.
- 1A for-each loop visits each character of the string in turn.
- 2
Character.isDigit(c)checks whether the current character is one of0through9. - 3A match increments the
countvariable; anything else is skipped. - 4After the loop,
countholds the total number of digits found.
"Order66Confirmed42", the scan finds four digit characters: 6, 6, 4, and 2.Key Point: Character.isDigit() checks the character itself, not the string as a number — it works just as well on digits embedded inside letters, like "Order66", as it would on a standalone number string.
Why: Each character is visited once, and only a single running counter is kept regardless of string length.
Key Concepts
Approach 2: Java 8
public class CountDigitsStream {
public static void main(String[] args) {
String str = "Order66Confirmed42";
// filter() keeps only digit character codes; count() reduces to a single total
long count = str.chars().filter(Character::isDigit).count();
System.out.println("Digits: " + count);
}
}
Output
Core Logic
The same digit check can filter a stream of character codes down to just the digits, then count what's left.
- 1
str.chars()returns anIntStreamof the string's character codes. - 2
.filter(Character::isDigit)keeps only the codes that represent a digit character. - 3
.count()reduces the filtered stream down to a singlelongtotal.
"Order66Confirmed42" keeps only 6, 6, 4, and 2, so count() returns 4.Key Point: Character::isDigit used as a method reference here is exactly the same check the loop version calls directly — streams just change how the filtering is expressed.
Why: The stream still visits every character once, and count() reduces straight down to a single long without collecting anything.