English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (List)

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input Output (I/O)

Java Reader/Writer

Java other topics

Java program to calculate the number of digits in an integer

Java Comprehensive Examples

In this program, you will learn to use while loop and for loop to calculate the number of digits in Java.

Example1: Count the number of digits in the integer using the while loop

public class NumberDigits {
    public static void main(String[] args) {
        int count = 0, num = 3452;
        while(num != 0)
        {
            // num = num/10
            num /= 10;
            ++count;
        }
        System.out.println("Number of digits: ", + count);
    }
}

When running this program, the output is:

Number of digits: 4

In this program, the while loop will be used in a loop until the calculation result of the test expression num != 0 is 0(false).

  • After the first iteration, num will be divided by10, its value will be345. Then, count will be incremented to1.

  • After the second iteration, the value of num will be34, and count will be incremented to2.

  • After the third iteration, the value of num will be3, and count will be incremented to3.

  • After the fourth iteration, the value of num will be 0, and count will be incremented to4.

  • Then evaluate the test expression as false and terminate the loop.

Example2: Count the number of digits in an integer using a for loop

public class NumberDigits {
    public static void main(String[] args) {
        int count = 0, num = 123456;
        for(; num != 0; num/=10, ++count) {   
        }
        System.out.println("Number of digits: ", + count);
    }
}

When running this program, the output is:

Number of digits: 6

In this program, instead of using a while loop, an empty for loop is used.

In each iteration, the value of num is divided by10, then count is incremented1.

If num != 0 is false, i.e., num = 0, the for loop exits.

Since the for loop has no body, it can be changed to a single statement in Java as follows:

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

Java Comprehensive Examples