Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Count Digits in Java

Count decimal digits in Java with repeated division by ten after Scanner input. Zero counts as one digit; minus signs and typed leading zeros do not count.

BeginnerJava Loop ProgramsExample 7 of 25
count-digits.java
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Enter a number: ");
7 long n = sc.nextInt();
8
9 if (n == 0) {
10 System.out.println("Digits = 1");
11 sc.close();
12 return;
13 }
14
15 n = Math.abs(n);
16 int count = 0;
17 while (n != 0) {
18 count++;
19 n /= 10;
20 }
21
22 System.out.println("Digits = " + count);
23 sc.close();
24 }
25}

Sample Output

Enter a number: 12345
Digits = 5

The values after division are 1234, 123, 12, 1, and 0. Each removal adds one to count, giving 5.

In this one

  • Count repeated divisions
  • Handle zero as one digit
  • Separate numeric length from typed text length

How it works

  1. 1

    Read an int into long n.

  2. 2

    If n is zero, print one digit and stop.

  3. 3

    Remove the sign with Math.abs.

  4. 4

    Count divisions by ten until n is zero.

Edge cases

Single zero

Enter 0

The early branch prints Digits = 1.

Leading zeros

Enter 0012

The numeric value is 12, so only two digits are counted.

What's going on

Count how many decimal digits a whole number contains. This can help check the length of a numeric entry before later processing. For example, 12345 contains five digits, while its minus sign would not count as a digit.

Scanner is the keyboard reader. Zero is handled first because the usual repeated-division loop would not run for it. For other inputs, the code removes the sign and repeatedly divides the working number by ten. Each pass removes one digit and increases count by one.

The sample takes five passes, so it prints Digits = 5. A wider long working value makes the sign removal safe even for the smallest int. Leading zeros are not retained by numeric input: typing 0012 gives a count of two. If every typed digit matters, such as in a roll number, read a string instead.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

How many digits does -456 have?

Pick an answer to check it.

Question 2

How many divisions reduce 12345 to zero?

Pick an answer to check it.

Questions people ask

Does a minus sign add to the count?

No. The code counts digits in the magnitude.

Why is zero special?

The condition n != 0 is false immediately for zero, but its written form still has one digit.

Will this count a 16-digit account number safely as input?

Not with nextInt. Read such identifiers as text rather than fitting them into this exercise's numeric input type.