Java Code to find number of digits in an integer

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.Let us consider some examples for better understanding :

Input : 4564

Output : Number of Digits = 4

Input : 0919878

Output :  Number of Digits = 7

So, now we create a java program to find number of digits. Implementation:-

Step 1 : Ask the user to enter an integer and store that integer value in a variable, number.

Step 2 : Declare a variable digit and initialize it with 0.

Step 3 : Use a while loop to pick the digits of the integer and count the number of digits one by one.

Step 4 : Use a statement to pick the last digit of the integer..

Step 5 : Increment the value of digit by 1.

Step 6 : Restore the value of number by removing last digit in every iteration of the loop.

Step 7 : Repeat the Steps from 3 to 6 till the value of number becomes 0.

Step 8 : Display the result. Java Program:-

//Java program to find number of digits in an integer
import java.util.Scanner;
public classnumber_of_digits
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);

//input from user
System.out.print("Enter an Integer : ");
int number = sc.nextInt();

//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);

//closing scanner class(not compulsory, but good practice)
sc.close();
}
}
Output:-
Enter an Integer : 32
Number of Digits = 2

Enter an Integer : 1239656
Number of Digits = 7