Java ProgramsControl FlowSum of Digits

Sum of Digits in Java

beginner·  Control Flow  ·  Loops

Problem

The sum of a number's digits is found by peeling off one digit at a time and adding each one into a running total.

Given a number, find the sum of its individual digits.

Input
12345
Output
Sum of digits: 15

Java Program

Java
public class SumOfDigits { public static void main(String[] args) { int n = 12345; int sum = 0; while (n > 0) { sum += n % 10; // add the last digit into the running total n /= 10; } System.out.println("Sum of digits: " + sum); } }

Output

Sum of digits: 15

Core Logic

Repeatedly pulling off the last digit with the modulo operator, and adding it into a running total, sums every digit without ever needing to know the number's length up front.

How It Works
  1. 1n % 10 extracts the current last digit of n.
  2. 2That digit is added into sum.
  3. 3n /= 10 removes the digit just processed, shifting the next one into place.
  4. 4The loop continues until n reaches 0, meaning every digit has been added.
For 12345, the digits 5, 4, 3, 2, 1 are peeled off one at a time and summed to 15.
💡

Key Point: The order digits are visited in — last to first — doesn't matter for a sum, since addition doesn't care about order.

Complexity
Time Complexity: O(d)Space Complexity: O(1)

Why: Each loop iteration strips exactly one digit off n, so the number of iterations equals n's digit count d, with only a running total kept.

Key Concepts

while loopmodulo operatordigit extraction

Approach 2: Java 8

Java
public class SumOfDigitsStream { public static void main(String[] args) { int n = 12345; // Converts each digit character back to its numeric value, then sums them int sum = String.valueOf(n).chars().map(c -> c - '0').sum(); System.out.println("Sum of digits: " + sum); } }

Output

Sum of digits: 15

Core Logic

Treating the number as a string of digit characters lets a stream sum them directly, without any manual arithmetic loop.

How It Works
  1. 1String.valueOf(n) converts the number into its digit string.
  2. 2.chars() streams each character's underlying code point.
  3. 3.map(c -> c - '0') converts each character code back into its numeric digit value.
  4. 4.sum() reduces the stream of digits down to a single total.
For 12345, the stream converts each character to its digit and sums them to 15, the same result the loop finds.
💡

Key Point: The c - '0' trick works because digit characters are laid out consecutively in code order, so subtracting '0' gives the digit's numeric value directly.

Complexity
Time Complexity: O(d)Space Complexity: O(1)

Why: The stream still visits each of the d digit characters once, converting and summing them without collecting anything.

Key Concepts

Streamchars()sum()

Related Programs