How to Find Sum of Digits of a Number in Java

The following Java program computes the sum of digits of a number. For example, if the input is 278, the output is calculated as 2+7+8 = 17. This function is useful in a number of numeric algorithms. For example,  IMEI check sum algorithm requires calculation of sum of digits. This problem is also given as an exercise for beginners in Java programming.

Algorithm for Finding Sum of Digits of a Number

We start by dividing the number with 10 and finding the remainder. The following program uses Java modulus operator for this. This gives us the right most digit. We then divide the number by 10 to remove the right most digit. This process is repeated until no more digits are left in the number. Each digit we extract is added to a separate variable to compute the sum.

Java Source Code for Finding Sum of Digits of a Number

The following Java program uses only core Java APIs.

import java.util.Scanner;

// Java program to find sum of digits of a number
public class SumOfDigitsInJava {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Please a number: ");
        int number = scanner.nextInt();

        int sumOfDigits = findSumOfDigits(number);
        System.out.println("Sum of digits of " + number + " is " + sumOfDigits);

        scanner.close();
    }

    // Find sum of digits of a number
    public static int findSumOfDigits(int number) {
        int sum = 0;
        while (number > 0) {
            int digit = number % 10;
            number = number / 10;
            sum += digit;
        }
        return sum;
    }
}

Here is a sample output of the above Java program,

java SumOfDigitsInJava
Please a number: 278
Sum of digits of 278 is 17