Sum of Digits in Java: Solution, 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

Validated solution

Reveal Java solution
public class Main {
    static int digitSum(int value) {
        value = Math.abs(value);
        int sum = 0;
        do {
            sum += value % 10;
            value /= 10;
        } while (value > 0);
        return sum;
    }

    public static void main(String[] args) {
        System.out.println("Sum of digits: " + digitSum(12345));
    }
}

How to approach the problem

Take the rightmost digit with % 10, add it to an accumulator, then discard that digit with integer division. A do-while loop makes the definition for zero explicit: its digit sum is zero.

Approach

  1. Keep the original value separate if a later check still needs it.
  2. Repeatedly add value % 10 to sum.
  3. Replace value with value / 10 until no digits remain.

Time and space complexity

Time: O(d), where d is the number of digits. Space: O(1).

Edge cases to test

  • 0 should return 0 rather than skipping the loop.
  • Math.abs(Integer.MIN_VALUE) overflows; use long for a fully general signed-int contract.

Common mistakes

  • Using / 10 before capturing the final digit.
  • Forgetting that negative inputs need a stated policy.

Follow-up challenge

Return the digital root without converting the number to text.

Related Core Java Basics exercises

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