How to sum digits of an integer in java?

Solution 1:

public static void main(String[] args) {
        int num = 321;
        int sum = 0;
        while (num > 0) {
            sum = sum + num % 10;
            num = num / 10;
        }
        System.out.println(sum); 
}

Output

6

Solution 2:

A simple solution using streams:

int n = 321;
int sum = String.valueOf(n)
    .chars()
    .map(Character::getNumericValue)
    .sum();