In this Java program, we’ll learn how to Count the Number of Digits in an Integer in your Java program.
How to Count Number of Digits in an Integer using JAVA?
Example 1: using for loop
RUN CODE SNIPPETpublic class Main { public static void main(String[] args) { int count = 0, num = 123456789; for (; num != 0; num /= 10, ++count) { } System.out.println("Number of digits: " + count); } }
OUTPUT
Number of digits: 9
In this program, we are using for loop without any body. In each iteration, the value of num is divided by 10 and the count is incremented by 1.
And the loop exists when num !=0.
Example 2: using while loop
RUN CODE SNIPPETpublic class Main { public static void main(String[] args) { int count = 0, num = 1020102050; while (num != 0) { num /= 10; ++count; } System.out.println("Number of digits: " + count); } }
OUTPUT
Number of digits: 10
In the above program, we have used while loop. The while loop is iterated until the test expression num !=0 is evaluated to 0.