Sum of Digits in Java: Explanation & Practice

Calculate the sum of all digits in a number

Problem summary

Write a program that calculates the sum of all digits 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 calculate sum of digits
        // Should work for ANY number, not just 12345
        // Print: Sum of digits: <result>
    }
}

Expected output and test cases

  • 12345 → 1+2+3+4+5 = 15
    Sum of digits: 15
  • 1234 → 1+2+3+4 = 10
    Sum of digits: 10
  • 123 → 1+2+3 = 6
    Sum of digits: 6

Hints

  1. Use a while loop to extract each digit
  2. number % 10 gives the last digit
  3. number / 10 removes the last digit

Related Core Java Basics exercises

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