Count Digits in Java: Explanation & Practice

Count the number of digits in an integer

Problem summary

Write a program that counts how many digits are in a given number. Your code should work for ANY positive integer.

Starter code

public class Main {
    public static void main(String[] args) {
        int number = 12345; // Test case 1
        
        // Write code to count digits
        // Should work for ANY positive number
        // Print: Digit count: <result>
    }
}

Expected output and test cases

  • 12345 has 5 digits
    Digit count: 5
  • 100 has 3 digits
    Digit count: 3
  • 7 has 1 digit
    Digit count: 1

Hints

  1. Keep dividing by 10 until the number becomes 0
  2. Count how many divisions it takes
  3. Handle the special case of 0 separately

Related Core Java Basics exercises

Practice all Core Java Basics exercises · Run this idea in the Java compiler