Java program to count number of digits in integer

Number of digits in 12345  is 5.

Example using while Loop

public class CountNumberOfDigit {

    public static void main(String[] args) {

        int count = 0, num = 12345;

        while(num != 0)
        {
            num /= 10; // num = num / 10;
            ++count;
        }
        System.out.println("Number of digits: " + count);
    }
}

Output

Number of digits: 5

Execution of program:

  1. count initalize to 0, num to 12345
  2. while loop body will execute if num != 0
  3. num = num /10; Here, 12345 /10 result in 1234.5 since num is integer decimal number is ignored.
  4. the value of num becomes 1234
  5. count will be increased to 1
  6. Loop will continue till num becomes 0 after statement 1/10 resulting in 0
  7. print function executed