Count Digits in a String in Java — Definition, Examples and Program

Learn how to count digits in a string using Java. This blog explains the logic with examples, a simple Java program, and practice challenges for beginners.

Count Digits in a String in Java — Definition, Examples and Program

Counting digits in a string is a common string-processing task. It helps in validating inputs like phone numbers, IDs, and mixed text data.

In this blog, you will learn:

What Are Digits?

Digits are numeric characters from 0 to 9.

How the Logic Works

To count digits in a string:

  1. Read the input string.
  2. Traverse each character of the string.
  3. Check whether the character is between '0' and '9'.
  4. Increase the digit count when a digit is found.

Example 1

Input: "Java123"

Total Digits: 3

Example 2

Input: "Room No 45A"

Total Digits: 2

Java Program to Count Digits


import java.util.Scanner;

public class CountDigits {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a string: ");
        String input = sc.nextLine();

        int digitCount = 0;

        for (int i = 0; i < input.length(); i++) {
            char ch = input.charAt(i);

            if (ch >= '0' && ch <= '9') {
                digitCount++;
            }
        }

        System.out.println("Number of digits: " + digitCount);
    }
}

Sample Output


Enter a string: hospitalRoom23
Number of digits: 2

Practice Challenges

  1. Modify the program to count letters, digits, and special characters separately.
  2. Check if a string contains only digits.
  3. Extract all digits from a string and form a number.

Counting digits is an essential skill for input validation and string analysis in Java. It forms the basis for many real-world applications.