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

In this Java program, we will learn how to find the GCD of two numbers using Java.  GCD (Greatest Common...
  • Java
  • December 3, 2024
In this Java Program, you’ll learn how to swap two numbers using the Java programming language.  How to Swap Two...
  • Java
  • December 2, 2024
In this Java program , we will learn how to Find Largest Element in an Array in your Java program.   How to Find Largest Element...
  • Java
  • December 2, 2024