Java Program to Count Number of Digits in an Integer

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 SNIPPET
public 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 SNIPPET
public 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. 

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

Java is a popular programming language that is used to develop a wide range of applications. If you are a...
  • Java
  • March 6, 2023
Java is a programming language and computing platform that is used to create various types of applications. It is used...
  • Java
  • March 6, 2023
In this post, you’ll learn how to download and install JUnit in Eclipse so that you can use in your...
  • Java
  • October 9, 2022