Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Sum of Digits in Java

Add a number's digits in Java by taking % 10 and dividing by ten in a while loop. Convert Scanner input to long before Math.abs to handle every int safely.

BeginnerJava Loop ProgramsExample 6 of 25
sum-of-digits.java
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Enter a number: ");
7 long n = Math.abs((long) sc.nextInt());
8
9 int sum = 0;
10 while (n != 0) {
11 sum += n % 10;
12 n /= 10;
13 }
14
15 System.out.println("Sum of digits = " + sum);
16 sc.close();
17 }
18}

Sample Output

Enter a number: 1234
Sum of digits = 10

The loop adds 4, then 3, then 2, then 1. The running totals are 4,7,9,10.

In this one

  • Accumulate a digit total
  • Remove digits with integer division
  • Ignore the sign safely

How it works

  1. 1

    Read an int into a wider positive working value.

  2. 2

    Start sum at zero.

  3. 3

    Add n % 10, then divide n by 10.

  4. 4

    Print sum when all digits are removed.

Edge cases

All zeros

Enter 0

The total remains zero, which is the sum of its only digit.

Negative number

Enter -123

The sign is removed first, so the digit total is 6.

What's going on

Add the decimal digits of a number rather than adding separate input numbers. For 1234, the total is 1 + 2 + 3 + 4 = 10. Digit totals are useful practice for number-processing checks such as the Harshad-number exercise.

Scanner is the keyboard reader. The program works on the magnitude, which means the value without its sign. It stores that working value in long so even the smallest int can be made positive safely. Each pass adds n % 10 to sum. % gives the remainder after division, which is the final digit for a non-negative number.

After reading a digit, n /= 10 removes it. The loop stops at zero and prints the accumulated sum. Zero naturally gives sum zero because the loop has nothing to add. Do not add n itself at each pass; that would add the shrinking whole values rather than the individual digits.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is the digit sum of 205?

Pick an answer to check it.

Question 2

What should sum start at?

Pick an answer to check it.

Questions people ask

Does the minus sign count as a digit?

No. This version sums only the numeric digits of the magnitude.

Does the order of digits matter?

No. 123 and 321 both have a digit sum of 6.

Why not use Math.abs on int first?

The smallest int cannot be made positive as an int. Converting to long before taking the absolute value avoids that problem.