Sum of digits of Given Number in Java

In this tutorial we will learn writing Java program to calculate the sum of its digit. We will also see writing digit sum program using Java 8.

Basically out agenda is to add the all digits of any number. So we will build our logic of the program accordingly.

Example:

Suppose use input is 2351 then our program should give output after adding 2, 3, 5 and 1.

2+3+5+1 = 11.

So our program should print output as 11.

Program 1: Find Sum of integer digits in Java

public class Main
{
	public static void main(String[] args) {
		int n = 2351;
		int sum=0;
		while(n!=0){
		    sum = sum + n%10;
		    n=n/10;
		}
		System.out.println(sum);
	}
}

Output

11

Program 2: Find Sum of integer digits using Java 8

public class Main {
    public static void main(String[] args) {
        int number = 12345;
        int sum = String.valueOf(number)
                .chars()
                .map(Character::getNumericValue)
                .sum();
        System.out.println(sum);
    }
}

Output

15

Conclusion

In this tutorial we have explored two different ways to write a program in java to find the sum of digits in a given integer. In the first program we have used traditional approach where we have used while loop to iterate through each digit of the number. And then summing summing them iteratively. This approach is straightforward and effective, providing a clear understanding of the logic behind digit summation.

In the second approach we have used Java 8 features to find the sum of digits. Here first we have converted the integer to a string. And then used chars() method and map(Character::getNumericValue) to get numeric value and using sum() method we have calculated final sum.