Sum of Digits in Java
Program to calculate the sum of digits of a number.
Last updated: 11 January 2026
Method 1: Using While Loop
Extract and add digits.
Main.javaRun in Compiler →
public class SumDigits {
public static void main(String[] args) {
int num = 1234;
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
System.out.println("Sum of Digits: " + sum);
}
}Output:
Sum of Digits: 10
Explanation
1 + 2 + 3 + 4 = 10.
Frequently Asked Questions
Try This Program
Copy this code and run it in our free online Java compiler.
Open Java Compiler