program to print the sum of all the digits of a given number in Java. We will find the sum of digits of a number in Java using for loop. The while loop also can be used for this purpose. We can also develop a Java program to calculate the sum of digits without using any loop.

Sum of Digits of a Number in Java Language
Using while loop
import java.util.Scanner;
public class SumOfDigitsProgram {
public static int digitSum(int number) {
// declare variables
int lastDigit = 0;
int sum = 0;
// loop to repeat the process
while(number != 0) {
// find last digit
lastDigit = number % 10;
// add last digit to sum
sum = sum + lastDigit;
// remove last digit
number = number / 10;
}
// sum value is the sum of digits
// of the given number
return sum;
}
public static void main(String[] args) {
// declare variables
int number = 0;
int sumOfDigits = 0;
// create Scanner class object
// for reading the values
Scanner scan = new Scanner(System.in);
// read input
System.out.print("Enter an integer number::");
number = scan.nextInt();
// find sum of digits of number
sumOfDigits = digitSum(number);
// display result
System.out.println("The sum of digits of" +
" the number "+number+" = "+sumOfDigits);
// close Scanner class object
scan.close();
}
}
The output for the different test-cases are:-
Enter an integer number:: 12345
The sum of digits of the number 12345 = 15
Enter an integer number:: 95423
The sum of digits of the number 95423 = 23
Types of Sorting Algorithms:
Additional Reading
- SEO Practices Everyone Should Follow SEO Rules
- Complete Top SEO Checklist
- Yoast Seo Premium 15.2 Nulled – WordPress SEO Plugin
- Top 50+ SEO Interview Questions
- What is a Backlink? How to Get More Backlinks
READ MORE
If you found this post useful, don’t forget to share this with your friends, and if you have any query feel free to comment it in the comment section.
Thank you 😊 Keep Learning !