Java Program to Count Number of Digits in an Integer

In this program we will learn using while loop and for loop and we will find the number of digits in an Integer.

Method 1: Count Number of Digits in an Integer using while loop

public class CountOfInteger{

  public static void main(String[] args) {

    int count = 0, num = 0003232;

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

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

Output

Number of digits: 4

Please note that zeros at the beginning of any Integer will be ignored and it will not be considered for count.

Method 2: Count Number of Digits in an Integer using for loop

public class CountOfIntegers{

  public static void main(String[] args) {

    int count = 0, num = 123456;

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

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

Output

Number of digits: 6

Leave a Reply