In this Java programming tutorials, I am going to show you how to calculate sum of digits till we get the single digit in java.

Input : Give any integer like : 658456

Output : 7

Sum of digits Example :

package com.onlinetutorialspoint.javaprograms;
import java.util.Scanner;
public class SumOfNumbers {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        long number, sum = 0, rem;
        System.out.print("Enter any number:");
        number = sc.nextLong();
        while (number >= 10) {
            sum = 0;
            while (number != 0) {
                rem = number % 10;
                number = number / 10;
                sum += rem;
            }
            if (sum >= 10) {
                number = sum;
            } else {
                break;
            }
        }
        System.out.println("Sum of Digits : " + sum);
    }
}

Output :

Enter a number:-658456
Sum of Digits : 7

About the Author:

Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment