Java Program to Count the Number of Digits in a Number

In this article, we will guide beginners through creating a Java program that counts the number of digits in a given number. 

The Concept

To determine the number of digits, a simple approach is to repeatedly divide the number by 10 until it becomes 0. 

Each division operation reduces one digit from the number, and the number of times we can perform this operation gives the count of digits. 

Java Program to Count the Number of Digits in a Number

import java.util.Scanner;

public class DigitCounter {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter your number:");
        int number = scanner.nextInt();

        int digitCount = countDigits(number);

        System.out.println("The number has " + digitCount + " digits.");
    }

    public static int countDigits(int number) {
        int count = 0;
        while (number != 0) {
            number /= 10;
            count++;
        }
        return count;
    }
}

Output:

Enter your number:
12345
The number has 5 digits.

Step by Step Explanation: 

Getting User Input:
We initialize the Scanner class to take an integer input from the user. 
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter your number:");
        int number = scanner.nextInt();
Counting Digits: 
    public static int countDigits(int number) {
        int count = 0;
        while (number != 0) {
            number /= 10;
            count++;
        }
        return count;
    }
The function countDigits is where the magic happens. We use a while loop to keep dividing the number by 10, and with each division, we increment the count by 1. This process continues until the number becomes 0. Once the loop exits, we return the count, which gives the number of digits. 

Displaying the Result:
        int digitCount = countDigits(number);
        System.out.println("The number has " + digitCount + " digits.");
We then print out the count of digits for the user to see.

Conclusion

Counting the digits of a number is a fundamental operation that not only introduces beginners to numerical manipulations in Java but also lays the foundation for more complex mathematical operations and algorithms. In this article, we saw creating a Java program that counts the number of digits in a given number. 

Related Java String Programs with Output

Comments