Java program to count number of digits in an integer

Count number of digits in an integer using while loop

We can count the number of digits in a given number in many ways using java.

One of the approach is that, we shall take the number, remove the last digit, and increment our counter for number of digits in the number. We can continue this, until there is no digit in the number.

Another approach is that, we can convert the given number into a string, and use the method string.length() to count the number of character in this string. This results in the number of digits in given number.

Here, while the loop is iterated until the test expression number != 0 is evaluated to 0(false).

After the first iteration, number will be divided by 10 and its value will be 345. Then, the count is incremented to 1.

After the second iteration, the value of number will be 34 and the count is increased to 2.

After the third iteration, the value of number will be 3 and the count is increased to 3.

After the fourth iteration, the value of number will be 0 and the count is increased to 4.

Then the test expression is evaluated to false and the loop terminates.

  • Program:

public class Main {

  public static void main(String[] args) {

    int count = 0, number = 0003452;

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

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

  • Output:

Number of digits: 4

0 comments