Sum of Array in Java: Solution, Explanation & Practice
Calculate the sum of array elements
Problem summary
Find the sum of all elements in the array [5, 10, 15, 20, 25].
Starter code
public class Main {
public static void main(String[] args) {
int[] numbers = {5, 10, 15, 20, 25};
// Calculate and print sum
// Print: Sum: <result>
}
}Expected output and test cases
- Sum of array
Sum: 75
Hints
- Initialize sum to 0
- Add each element to sum
- Use for-each or regular for loop
Validated solution
Reveal Java solution
public class Main {
static int sum(int[] values) {
int total = 0;
for (int value : values) total += value;
return total;
}
public static void main(String[] args) {
int[] values = {5, 10, 15, 20, 25};
System.out.println("Sum: " + sum(values));
}
}How to approach the problem
A running total is the smallest state needed. After each iteration it equals the sum of every value already visited, which makes the empty-array result naturally zero.
Approach
- Start with the additive identity, zero.
- Visit each element once.
- Add the current value to the running total.
Time and space complexity
Time: O(n). Space: O(1).
Edge cases to test
- An empty array has sum zero.
- Many large ints can overflow int; promote total to long when required.
Common mistakes
- Initializing total to the first element and then failing on empty input.
- Using a nested loop and counting values repeatedly.
Follow-up challenge
Return both the sum and an overflow-safe average as a small result object.
Related Arrays exercises
- Practice Declare and Print Array in Java
- Practice Find Maximum in Java
- Practice Calculate Average in Java
Practice all Arrays exercises · Run this idea in the Java compiler