Java Code to find number of digits in an integer

number of digits in an integer using java

To find Number of digits in an integer using java

In this article we will count the number of digits in an integer using java . We will use the loop and a variable to count the number of digits.

Method Discussed :

  • Method 1 : Using loop
  • Method 2 : Using formulae.

Let’s discuss above two methods in brief,

Method 1 :

  • Declare a variable digit and initialize it with 0.
  • Use a while loop to pick the digits of the integer and count the number of digits one by one.
  • Use a statement to pick the last digit of the integer.
  • Increment the value of digit by 1.
  • Restore the value of number by removing last digit in every iteration of the loop.
  • Repeat the Steps from 3 to 6 till the value of number becomes 0.
  • Display the result.

Method 1 : Java Code:-

Run
//Java program to find number of digits in an integer
import java.util.Scanner;
class Main{	
public static void main(String[] args)
	{
		int number = 12345;

		//declare a variable to count number of digits
		int digit = 0;
		while(number != 0)
		{
			//pick last digit of the number and count one by one
			int pick_last = number % 10;
			digit++;
			number = number / 10;
		}

		//display number of digits
		System.out.print("Number of Digits = "+digit);

	}
}

Output

Number of Digits = 5

Method 2 :

In this method we will simple use the mathematical formulae,

  • No. of digits : (int)(Math.log10(number))+1

Method 2 : Java Code:-

Run
//Java program to find number of digits in an integer
import java.util.*;
 
class Main{	
public static void main(String[] args)
	{
		int number = 12345;
		
		int digit = (int)(Math.log10(number))+1;
		

		//display number of digits
		System.out.print("Number of Digits = "+digit);

	}
}

Output

Number of Digits = 5