For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
In Java, the sum of digits is calculated by using the modulus operator (%) to get each digit and adding it to a total. Then, the number is divided by 10 to remove the last digit, and this repeats until the number becomes zero. The challenge isn't efficiency but handling big integers beyond int and long limits, which is addressed using BigInteger.
In this guide, you’ll walk you through different methods, including the sum of digits of a number in Java using for loop. By the end, you'll have a solid understanding of how to solve this problem with ease.
Improve your Java programming skills with our Software Development courses — take the next step in your learning journey!
In this tutorial, you'll learn how to calculate the sum of digits of a number in Java with example, using several methods. You’ll explore straightforward techniques like using loops, and delve into the sum of digits of a number in Java using for loop, among others. Each method will be explained with code examples, so you can understand how to implement them in your own projects.
Different approaches offer trade-offs in readability and performance.
Let's dive into the first method: using a for loop to tackle this task step by step.
Let’s start with one of the most common and easy-to-understand methods to calculate the sum of digits of a number in Java — using a for loop. This approach is great for beginners because it gives you a hands-on understanding of how loops work, while also solving the problem efficiently.
Step-by-Step Explanation
To calculate the sum of digits of a number using a for loop, you first need to extract each digit from the number. You can do this by repeatedly dividing the number by 10, until the number becomes zero. The remainder of each division will give you the last digit of the number.
Code Example
public class SumOfDigits {
public static int sumOfDigits(int num) {
int sum = 0;
num = Math.abs(num); // Make sure the number is positive
// Loop through each digit
for (; num > 0; num /= 10) {
sum += num % 10; // Add the last digit to sum
}
return sum;
}
public static void main(String[] args) {
int number = 123;
System.out.println("Sum of digits: " + sumOfDigits(number));
}
}
Output:
Sum of digits: 6
Code Breakdown:
Edge Cases
When working with the sum of digits, it's important to consider edge cases:
Time Complexity
This method runs in O(d) time since we process each digit by repeatedly dividing by 10.
For example, for a number like 123456, the loop will run six times (one for each digit). As the size of the number increases, the number of iterations grows linearly, making this approach quite efficient for most practical purposes.
While both loops serve a similar purpose, the while loop works differently in terms of its structure, and it’s useful to understand both.
Step-by-Step Explanation
In this method, the basic idea remains the same: you need to extract each digit of the number and add it to a sum. The key difference is how the loop works. With a while loop, you continue extracting digits as long as the number is greater than zero.
Code Example
public class SumOfDigits {
public static int sumOfDigits(int num) {
int sum = 0;
num = Math.abs(num); // Ensure the number is positive
// Loop through each digit
while (num > 0) {
sum += num % 10; // Add the last digit to sum
num /= 10; // Remove the last digit
}
return sum;
}
public static void main(String[] args) {
int number = 987;
System.out.println("Sum of digits: " + sumOfDigits(number));
}
}
Output
Sum of digits: 24
This is because 9 + 8 + 7 = 24.
Code Breakdown:
Edge Cases
Just like with the for loop method, we need to consider edge cases:
Optimizing for Large Numbers
If you're working with numbers larger than long (19+ digits), consider using Java’s BigInteger class. This class can handle numbers that are far larger than what int or long can accommodate.
You can apply the same logic using BigInteger, and it will still work for calculating the sum of digits, no matter how large the number is.
Here’s how you could modify the code to use BigInteger:
import java.math.BigInteger;
public class SumOfDigits {
public static int sumOfDigits(BigInteger num) {
int sum = 0;
// Loop through each digit
while (num.compareTo(BigInteger.ZERO) > 0) {
sum += num.mod(BigInteger.TEN).intValue(); // Add the last digit to sum
num = num.divide(BigInteger.TEN); // Remove the last digit
}
return sum;
}
public static void main(String[] args) {
BigInteger bigNum = new BigInteger("12345678901234567890");
System.out.println("Sum of digits: " + sumOfDigits(bigNum));
}
}
Output:
For the input number 12345678901234567890, the output will be:
Sum of digits: 90
Time Complexity
The time complexity of the while loop method is O(d), where d is the number of digits in the input number. This is similar to the for loop method.
In both cases, the time complexity depends on the number of digits, and you will see a linear increase in iterations as the size of the number grows.
When working with BigInteger, while the approach still operates in linear time, the actual performance will be slower compared to primitive types like int, due to the overhead of handling very large numbers. However, this is an acceptable trade-off for most applications if you need to deal with large numbers.
Also Read: 50 Java Projects With Source Code in 2025: From Beginner to Advanced
You can use the recursion technique to repeatedly extract the last digit of a number and add it to the sum, reducing the number at each step.
Step-by-Step Explanation
To calculate the sum of digits using recursion, we:
Code Example
public class SumOfDigits {
public static int sumOfDigits(int num) {
// Base case: if the number is less than 10, return the number itself
if (num < 10) {
return num;
}
// Recursive case: sum the last digit and recursively call on the remaining number
return num % 10 + sumOfDigits(num / 10);
}
public static void main(String[] args) {
int number = 456;
System.out.println("Sum of digits: " + sumOfDigits(number));
}
}
Output
Sum of digits: 15
This is because 4 + 5 + 6 = 15.
Code Breakdown:
Edge Cases
Time Complexity
The time complexity of the recursive method is O(d), where d is the number of digits in the number. This is because the recursion operates by repeatedly dividing the number by 10, which reduces the size of the number by one digit per recursive call.
However, recursion in Java has an overhead because each method call requires stack space. If the number of digits is very large, deep recursion can lead to StackOverflowError. This is one of the reasons why using recursion for problems like this may not always be the best choice, especially when working with large numbers.
Best Practices for Recursion
While recursion is a neat and elegant solution, there are a few best practices to keep in mind:
Also Read: Top 12 Pattern Programs in Java You Should Checkout Today
In this method, we'll use Java’s ability to convert a number to a string to calculate the sum of its digits. This approach is particularly handy when you want to treat the number as a collection of characters, making it easy to extract each digit.
By converting the number to a string, we can simply iterate over each character, convert it back to an integer, and sum them up.
Step-by-Step Explanation
The process of summing the digits of a number using string conversion involves:
By treating the number as a string, each character can be easily converted to an integer using Character.getNumericValue().
Code Example
public class SumOfDigits {
public static int sumOfDigits(int num) {
// Convert the number to a string and handle negative numbers
String numStr = String.valueOf(Math.abs(num));
int sum = 0;
// Loop through each character in the string
for (int i = 0; i < numStr.length(); i++) {
sum += Character.getNumericValue(numStr.charAt(i)); // Add the digit to the sum
}
return sum;
}
public static void main(String[] args) {
int number = 12345;
System.out.println("Sum of digits: " + sumOfDigits(number));
}
}
Output
Sum of digits: 15
This is because 1 + 2 + 3 + 4 + 5 = 15.
Code Breakdown:
Edge Cases
Optimizing for Large Numbers
Java’s primitive data types like int and long can only handle numbers up to a certain size. If you are working with extremely large numbers, consider using Java’s BigInteger class, which can handle arbitrarily large integers. When using BigInteger, the method can still work in the same way by converting the number to a string.
Here's an example using BigInteger:
import java.math.BigInteger;
public class SumOfDigits {
public static int sumOfDigits(BigInteger num) {
String numStr = num.toString(); // Convert BigInteger to string
int sum = 0;
// Loop through each character in the string
for (int i = 0; i < numStr.length(); i++) {
sum += Character.getNumericValue(numStr.charAt(i)); // Add the digit to the sum
}
return sum;
}
public static void main(String[] args) {
BigInteger bigNum = new BigInteger("123456789012345678901234567890");
System.out.println("Sum of digits: " + sumOfDigits(bigNum));
}
}
Output
For the input number 123456789012345678901234567890, the output will be:
Sum of digits: 135
Time Complexity
The time complexity of this method is O(d), where d is the number of digits in the input number. This is because the time taken to loop through each character of the string is proportional to the number of digits in the number.
However, string conversion has a higher overhead compared to looping methods. The process of converting a number to a string (and vice versa) takes additional time and resources, which can make this method slower than using loops, especially for smaller numbers.
Also Read: String Functions In Java | Java String [With Examples]
For large numbers, though, using BigInteger ensures that we can handle numbers that exceed the limits of primitive types.
Java 8 introduced Streams, a powerful tool for functional programming that allows you to work with collections of data in a more declarative way. Using Streams to calculate the sum of digits is a modern approach that leverages the power of functional programming, making the code more concise and readable.
Step-by-Step Explanation
The idea behind using Streams is to:
This approach is clean, efficient, and makes use of Java's built-in libraries for functional programming.
Code Example
import java.util.stream.*;
public class SumOfDigits {
public static int sumOfDigits(int num) {
// Convert number to string and use streams to process each character
return String.valueOf(Math.abs(num)) // Convert number to string and handle negative numbers
.chars() // Create an IntStream of characters
.map(Character::getNumericValue) // Convert characters to their numeric value
.sum(); // Sum the values of the digits
}
public static void main(String[] args) {
int number = 9876;
System.out.println("Sum of digits: " + sumOfDigits(number));
}
}
Output
Sum of digits: 30
This is because 9 + 8 + 7 + 6 = 30.
Code Breakdown:
Edge Cases
Optimizing for Large Numbers
Java 8 Streams are quite powerful but are not optimized for performance in every case. For extremely large numbers, where performance is crucial, it’s important to remember that Streams introduce some overhead. However, for most practical purposes, using Streams will be efficient enough.
The BigInteger class has its own methods that support functional operations, but you can also use Streams for large numbers, just as we did with primitive types.
Code Example with BigInteger
import java.math.BigInteger;
import java.util.stream.*;
public class SumOfDigits {
public static int sumOfDigits(BigInteger num) {
// Convert BigInteger to string and use streams to process each character
return num.toString() // Convert BigInteger to string
.chars() // Create an IntStream of characters
.map(Character::getNumericValue) // Convert characters to their numeric value
.sum(); // Sum the values of the digits
}
public static void main(String[] args) {
BigInteger bigNum = new BigInteger("123456789012345678901234567890");
System.out.println("Sum of digits: " + sumOfDigits(bigNum));
}
}
Output
For the input number 123456789012345678901234567890, the output will be:
Sum of digits: 135
Time Complexity
The time complexity of this method is O(d), where d is the number of digits in the input number, just like the previous methods.
However, Streams have a slight overhead compared to simple loops due to their functional nature and additional processing steps. For small numbers, this overhead is negligible, but for large numbers, the performance might be slightly impacted compared to a simple loop-based solution.
Also Read: Exploring the 14 Key Advantages of Java: Why It Remains a Developer's Top Choice in 2025
Now that we've explored various methods, let’s compare them and find out which one suits your needs best.
Looking at this comparison will help you choose the method that best fits your needs based on performance, readability, and the size of the numbers you're working with.
Here’s a side-by-side performance breakdown:
Method | Pros | Cons | Time Complexity |
For Loop | Simple, easy to understand, and efficient for small to medium numbers. | Requires manual digit extraction; not the most modern approach. | O(d) |
While Loop | Similar to the for loop but offers flexibility in control. | Slightly less intuitive compared to a for loop. | O(d) |
Recursion | Elegant and functional; great for learning recursion. | Can lead to stack overflow errors with deep recursion; less efficient. | O(d) |
String Conversion | Very clean and readable; easy to implement. | Slightly slower due to string manipulation; overhead for conversion. | O(d) |
Streams (Java 8+) | Modern, concise, and functional programming style. | Introduces overhead compared to basic loops; not the most efficient for large numbers. | O(d) |
Now that we've compared the methods, let's move on to some best practices to keep your code clean, efficient, and error-free.
Let’s go over some key best practices that will help you write cleaner, more efficient Java code when summing digits.
When writing a method to calculate the sum of digits of a number in Java, make sure your variable and method names are clear.
For example, name your method sumOfDigits(int num) and avoid using vague names like sum or temp. This makes your code easier to understand and maintain.
Your function for calculating the sum of digits should focus solely on summing digits. Don’t mix it with other responsibilities, like validating user input or formatting output. This follows the Single Responsibility Principle and makes your code cleaner.
For example, sumOfDigits(int num) should just return the sum, not deal with other tasks.
Always consider edge cases like negative numbers, zero, and very large numbers. For example, when calculating the sum of digits of a number in Java with example, ensure negative numbers are converted to positive values using Math.abs(num) to avoid incorrect results.
Also, consider what happens when the number is zero. In that case, your method should return 0.
While loops are the most efficient computationally, streams add readability but introduce minor overhead. If performance is a concern, especially with large integers, try to avoid string conversion or recursion, as they introduce unnecessary overhead.
Use the for loop or while loop for better control over the process and memory.
When summing digits, avoid using unnecessary data structures like arrays or lists unless your problem specifically requires them.
For example, converting the number to a string is handy, but it’s not always the most memory-efficient way, especially when you’re only interested in the digits. Stick to simpler structures like integers or loops whenever possible.
As with any function, make sure to test your sum of digits function with various inputs. Test it with:
Even if your code is simple, add comments where necessary, especially if you're using recursion or more complex approaches like sum of digits of a number in Java using for loop.
For example, explain how the loop works and why you're using num % 10 to get the last digit.
Remember, the goal is to write code that is easy to understand, efficient to run, and free of errors—whether you’re summing digits or tackling more complex problems!
Test your understanding of summing digits in Java with these questions! From basic concepts to advanced methods, let's see how well you grasp the techniques.
1. What is the primary purpose of calculating the sum of digits of a number in Java?
A) To convert a number to a string
B) To perform mathematical operations
C) To extract individual digits and sum them
D) To find the maximum digit in a number
2. Which of the following methods can be used to sum the digits of a number in Java?
A) Using a for loop
B) Using a while loop
C) Using recursion
D) All of the above
3. What is the result of summing the digits of the number 459 in Java?
A) 18
B) 15
C) 13
D) 9
4. How can you handle negative numbers when summing digits in Java?
A) Convert the number to a positive using Math.abs()
B) Ignore the negative sign
C) Treat negative numbers as zero
D) Use a different method for negative numbers
5. Which method is best suited for handling extremely large numbers when summing digits in Java?
A) Using recursion
B) Using the string conversion method
C) Using a for loop
D) Using BigInteger class
6. What is the time complexity of the method for summing digits in Java using a for loop?
A) O(1)
B) O(d)
C) O(n^2)
D) O(log n)
7. Which method for summing digits in Java can lead to a stack overflow error if used with large numbers?
A) For loop
B) While loop
C) Recursion
D) String conversion
8. How does the string conversion method work when summing digits in Java?
A) By converting the number to a string and summing the ASCII values
B) By converting the number to a string and summing the individual characters' numeric values
C) By using a loop to extract digits from the string
D) By converting the digits to integers and summing them using a for loop
9. Which of the following is a limitation of using recursion for summing digits in Java?
A) It is less readable
B) It requires additional memory for each recursive call
C) It can be slower than a for loop
D) It cannot handle negative numbers
10. How can the sum of digits of a number be calculated efficiently in Java for both small and large numbers?
A) Using recursion
B) Using a while loop with manual digit extraction
C) Using string conversion for better readability
D) Using a combination of BigInteger and string conversion
Also Read: Top 13 String Functions in Java | Java String [With Examples]
You can further enhance your Java skills by practicing summing digits techniques and exploring advanced Java methods, helping you master real-world applications and strengthen your programming expertise.
Dive into advanced Java techniques for summing digits, including efficient methods like loops, recursion, and string conversion. Gain hands-on experience with different approaches, which are essential for building optimized, high-performance applications that handle a variety of numerical tasks.
Explore more Java concepts and deepen your understanding of real-world applications to enhance your programming skills.
Below are some relevant upGrad courses:
You can also receive personalized career guidance with upGrad to help navigate your career path, or visit your nearest upGrad center to begin practical, hands-on training today!
Similar Reads:
You can improve performance by using the most efficient methods like the sum of digits of a number in Java using for loop instead of recursion or string conversion, especially for large numbers.
For most cases, using the sum of digits of a number in Java using for loop is more efficient, as recursion may cause stack overflow for large numbers.
Yes, you can use BigInteger in Java to handle extremely large numbers and calculate the sum of digits of a number in Java with example efficiently.
Convert the number to a string and sum the digits before the decimal point. Alternatively, extract the integer part first and handle the digits separately.
Yes, you can handle negative numbers by converting them to their absolute value before summing the digits.
The time complexity is O(d), where d is the number of digits in the number being processed.
You can directly use a mathematical approach like the sum of digits of a number in Java using for loop, iterating through the digits by dividing the number by 10.
Leading zeros are not stored in integers, but you can handle them by converting the number to a string first.
Iterate through the array, converting each element to an integer and summing them up using a loop or recursion.
Yes, for large datasets, methods like recursion or string conversion might be slower; using sum of digits of a number in Java using for loop is more efficient.
Yes, Java streams provide a functional approach to summing digits by converting the number to a string and using stream operations like mapToInt() to sum the digits.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.