Java Program to Count Total Number of Digits in an Integer

Learn how to count total number of digits in an integer using a while loop in Java . Includes source code, explanation, output, and examples.

Code Explanation (Step-by-Step)

  • Initialize an integer variable num with the value 12345.
  • Create a variable count and initialize it to 0.
  • Use a while loop that runs until num becomes 0.
  • Divide the number by 10 in each iteration using num = num / 10.
  • Increment the count variable after each division.
  • Continue the process until all digits are removed.
  • Print the value of count, which represents the total number of digits.
				
					public class CountOfDigit {

    public static void main(String[] args) {

        int num = 12345;
        int count = 0;

        while (num != 0) {
            num = num / 10;
            count++;
        }

        System.out.println("Total Number of Digits: " + count);
    }
}
				
			

Output :-
Total Number of Digits: 5

What Is Digit Counting in Java?

Digit counting in Java is the process of determining how many digits are present in a number. A common approach is to repeatedly divide the number by 10 until it becomes 0. Each division removes the last digit, and a counter keeps track of the total number of digits.
				
					public class CountDigitsUsingLength {

    public static void main(String[] args) {

        int num = 12345;

        String str = String.valueOf(num);

        int count = str.length();

        System.out.println("Total Number of Digits: " + count);
    }
}
				
			

Output :-
Total Number of Digits: 5