Calculating Sum of Digits in Java: Loop and Stream Techniques

Dec 02, 2025 · Programming · 29 views · 7.8

Keywords: Java | digit sum | loop | modulus operator | stream

Abstract: This article provides a detailed comparison of two methods to calculate the sum of digits of an integer in Java: a traditional loop-based approach using modulus operator and a modern stream-based approach. The loop method is efficient with O(d) time complexity, while the stream method offers conciseness. Code examples and analysis are included.

Introduction

In Java programming, summing the digits of an integer is a fundamental problem often encountered in exercises. This article explores two efficient methods to accomplish this task.

Core Method: Using a While Loop with Modulus Operator

Based on the accepted answer, the most straightforward approach involves a while loop and the modulus operator to extract and sum digits. The algorithm steps include: initializing a sum variable to 0; while the number is greater than 0, repeatedly adding the last digit (obtained by num % 10) to sum, and removing the last digit by dividing the number by 10 (num = num / 10); finally, outputting the sum.

Code example:

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

Analysis of the Loop-Based Method

This method has a time complexity of O(d), where d is the number of digits, and a space complexity of O(1). It uses constant extra space, making it efficient and widely applicable in various scenarios.

Alternative Method: Using Java Streams

Another approach, as shown in the supplementary answer, leverages Java streams for a more concise solution. It first converts the integer to a string, then uses the chars() method to get a stream of characters, maps each character to a numeric value with map(Character::getNumericValue), and finally sums them with sum().

Code example:

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

This method is elegant but may be less efficient for large numbers due to the overhead of string conversion.

Conclusion

Both methods are effective for calculating the sum of digits in Java. The loop-based method is preferred for its simplicity and efficiency, while the stream-based method offers a functional programming style. Developers can choose based on their specific needs.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.