Java Array Program · A03
Sum of Array Elements in Java
Adding numbers is easy; adding them without overflow is the real lesson. See why the total should be a long even when the elements are int.
Problem Statement
Write a method that returns the sum of all elements of an int array. The elements can be negative.
The sum of many int values can exceed the int range, so the method returns a long. The sum of an empty array is 0.
Input/Output Examples
[4, 8, 15, 16]Output43Explanation: 4 + 8 + 15 + 16 = 43.[]Output0Explanation: adding no numbers gives 0.[2000000000, 2000000000]Output4000000000Explanation: the total is larger than Integer.MAX_VALUE, so it needs a long.Visual Explanation
[4, 8, 15, 16]: each tag shows the running total after that element is added.The running total starts at 0 and grows by one element per step. Because the total is a long, each int is widened before it is added, so the result cannot overflow.
Approaches
Both approaches add every element once. The key difference from a naive version is the type of the total.
Approach 1: Loop With a long Total (Recommended)
Idea: add each element to a long variable with an enhanced for loop.
- Set
long total = 0. - For each element, do
total += value. - Return
total.
Time: O(n) · Space: O(1).
Approach 2: LongStream sum()
Idea: convert the IntStream to a LongStream with asLongStream(), then call sum().
- Create an
IntStreamwithArrays.stream(arr). - Widen it with
asLongStream(). - Call
sum().
Time: O(n) · Space: O(1).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Loop With a long Total (Recommended)
An empty array never enters the loop, so it returns 0 with no special case.
import java.util.Arrays;
public class ArraySumLoop {
// A long total cannot overflow for any int[] that fits in memory
static long sum(int[] arr) {
long total = 0;
for (int value : arr) {
total += value;
}
return total;
}
public static void main(String[] args) {
int[][] inputs = {{4, 8, 15, 16}, {}, {2000000000, 2000000000}};
for (int[] arr : inputs) {
System.out.println(Arrays.toString(arr) + " -> " + sum(arr));
}
}
}
[4, 8, 15, 16] -> 43 [] -> 0 [2000000000, 2000000000] -> 4000000000
Time complexity: O(n) · Space complexity: O(1).
Approach 2: LongStream sum()
Arrays.stream(arr).sum() alone returns an int and silently overflows for the third example. Widening first fixes that.
import java.util.Arrays;
public class ArraySumStream {
// asLongStream() widens each value first; IntStream.sum() would overflow
static long sum(int[] arr) {
return Arrays.stream(arr).asLongStream().sum();
}
public static void main(String[] args) {
int[][] inputs = {{4, 8, 15, 16}, {}, {2000000000, 2000000000}};
for (int[] arr : inputs) {
System.out.println(Arrays.toString(arr) + " -> " + sum(arr));
}
}
}
[4, 8, 15, 16] -> 43 [] -> 0 [2000000000, 2000000000] -> 4000000000
Time complexity: O(n) · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Loop With a long Total | O(n) | O(1) |
| LongStream sum() | O(n) | O(1) |
Here n is the number of elements. Each element is added once, and the only extra storage is the running total.
Interview Tips and Recommended Approach
- Mention overflow before the interviewer does.
int totalwraps around without an error;2000000000 + 2000000000becomes-294967296. - Know that
IntStream.sum()returns anint. UseasLongStream()ormapToLong()when the total might be large. - State the empty-array result. The sum of nothing is
0, and your loop should return it without a special case. - Prepare the follow-ups: average, sum of even elements, and prefix sums all build on this loop.
Recommended Approach: Loop With a long Total
Why: it is a single readable loop, it returns 0 for an empty array naturally and the long total removes the overflow problem. It also makes the type choice visible, which interviewers often probe.