Java ProgramsStringsCount Digits in a String

Count Digits in a String in Java

beginner·  Strings  ·  String

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.

Input
Order66Confirmed42
Output
Digits: 4

Java Program

Java
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

Digits: 4

Core Logic

A single pass through the string, checking each character with Character.isDigit(), is enough to tally every digit.

How It Works
  1. 1A for-each loop visits each character of the string in turn.
  2. 2Character.isDigit(c) checks whether the current character is one of 0 through 9.
  3. 3A match increments the count variable; anything else is skipped.
  4. 4After the loop, count holds the total number of digits found.
For "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.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

Why: Each character is visited once, and only a single running counter is kept regardless of string length.

Key Concepts

Character.isDigit()for-each loopcounter variable

Approach 2: Java 8

Java
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

Digits: 4

Core Logic

The same digit check can filter a stream of character codes down to just the digits, then count what's left.

How It Works
  1. 1str.chars() returns an IntStream of the string's character codes.
  2. 2.filter(Character::isDigit) keeps only the codes that represent a digit character.
  3. 3.count() reduces the filtered stream down to a single long total.
Filtering "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.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

Why: The stream still visits every character once, and count() reduces straight down to a single long without collecting anything.

Key Concepts

Streamchars()filter()count()

Related Programs