Find Sum of Digits in Java

Beginner
⏱️ 8 min read
📚 Updated: May 2026
🎯 2 Code Examples
Number manipulation

What you’ll learn

  • How to extract digits using % 10 and / 10.
  • The accumulator pattern: sum += digit.
  • How to handle negatives and zero safely.

Overview

To find the sum of digits, repeatedly take the last digit and add it to a running total. For 12345, the result is 15.

Two Java examples

Fixed number and user-input number versions.

Live preview

Type values like 12345 or -802.

Next step

Repeated digit sums lead to digital root.

Live preview

Enter an integer and see its digits and their sum.

Works for negatives by using absolute value.

Live result
Press “Compute sum”.

Algorithm

Goal: compute sum of all decimal digits of n.

Normalize sign

Take absolute value first.

Extract digits

Use n % 10 and n / 10 in a loop.

Accumulate

Add each digit to running sum.

📜 Pseudocode

Pseudocode
function sumOfDigits(n):
  n = abs(n)
  if n == 0:
    return 0
  sum = 0
  while n > 0:
    sum = sum + (n mod 10)
    n = floor(n / 10)
  return sum
1

Sum of digits (fixed number)

This example calculates sum of digits for 12345.

java
public class Main {
    static int sumOfDigits(int n) {
        n = Math.abs(n);
        int sum = 0;
        while (n > 0) {
            sum += n % 10;
            n /= 10;
        }
        return sum;
    }

    public static void main(String[] args) {
        int number = 12345;
        System.out.println("Sum of digits of " + number + " is: " + sumOfDigits(number));
    }
}
2

Sum of digits (user input)

This version reads an integer and prints its digit sum.

java
import java.util.Scanner;

public class Main {
    static int sumOfDigits(int n) {
        n = Math.abs(n);
        int sum = 0;
        while (n > 0) {
            sum += n % 10;
            n /= 10;
        }
        return sum;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        if (!sc.hasNextInt()) {
            System.out.println("Invalid input.");
            return;
        }
        int number = sc.nextInt();
        System.out.println("Sum of digits: " + sumOfDigits(number));
    }
}

Optimization notes

Use string conversion for readability, or arithmetic loop for interview-style constant space.

❓ FAQ

Take the last digit using n % 10, add it to sum, then remove the last digit using n / 10. Repeat until n becomes 0.
Yes. The sum of digits of 0 is 0.
Take absolute value first, then apply the same loop.
O(d), where d is the number of digits.
Yes. Digit sum is the first step; digital root repeats digit sum until one digit remains.

🔄 Input / output examples

InputDigit sum
1234515
00

Edge cases and pitfalls

Common mistakes are around zero, sign handling, and absolute-value edge cases.

n = 0

Return zero

When input is zero, digit sum should be zero.

Negative

Ignore sign

Use absolute value before extracting digits.

INT_MIN

Advanced overflow case

For extreme negative int limits, use a wider type if needed.

⏱️ Time and space complexity

TaskTimeExtra space
Sum digits of one numberO(d) (d = number of digits)O(1)

Summary

  • Core loop: sum += n % 10, then n /= 10.
  • Sign handling: use absolute value for negative numbers.
  • Complexity: linear in number of digits.
Did you know?

Repeatedly summing digits until one digit remains is called finding the digital root.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful