;

Java Program to Count the Number of Digits in an Integer


Tutorialsrack 26/06/2021 Java

In this Java program, you’ll learn how to count the number of digits in an Integer. This post explains two ways to count the number of digits in an integer: while and for loop 

Here are the examples to count the number of digits in an integer in Java.

Example 1: Java Program to Count Number of Digits in an Integer using While Loop

In this program, you will see how to count the number of digits in an integer using a while loop.

Example 1: Java Program to Count Number of Digits in an Integer using While Loop
// Java Program to Count Number of Digits in an Integer using While Loop

import java.util.Scanner;

public class JavaPrograms {

	public static void main(String[] args) {

		int count = 0;
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter a number: ");
		int num = sc.nextInt();

		// closing scanner class(not compulsory, but good programming practice)
		sc.close();
		while (num != 0) {
			// num = num/10
			num /= 10;
			++count;
		}

		System.out.println("Number of digits in the entered integer are: " + count);
	}
}
Output

Enter a number: 

00564646554

Number of digits in the entered integer are: 9

Example 2: Java Program to Count Number of Digits in an Integer using For Loop

In this program, you will see how to count the number of digits in an integer using for loop.

Example 2: Java Program to Count Number of Digits in an Integer using For Loop
//Java Program to Count Number of Digits in an Integer using For Loop

import java.util.Scanner;

public class JavaPrograms {

	public static void main(String[] args) {

		int count = 0;
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter a number: ");
		int num = sc.nextInt();

		// closing scanner class(not compulsory, but good programming practice)
		sc.close();
		for (; num != 0; num /= 10, ++count) {
	    }

		System.out.println("Number of digits in the entered integer are: " + count);
	}
}
Output

Enter a number: 

5432134

Number of digits in the entered integer are: 7


Related Posts



Comments

Recent Posts
Tags