Title: Sum of All Elements in an Array
Adding up the elements of an array is one of the first exercises every Java learner meets, and it quietly introduces the loop, the accumulator pattern, and the subtle traps of integer overflow all at once. In this guide, you’ll learn how to write a clean, compilable Java program that returns the sum of any int[], you’ll walk through its execution one iteration at a time, and you’ll finish with the edge cases and follow-up questions a strong candidate is expected to raise in an interview.
Understanding the Problem
Given an array of integers, we want to return a single integer equal to the total of every element in that array. For the input {10, 20, 30, 40, 50}, the expected output is 150. An empty array has a sum of 0 by convention, since adding no numbers produces the additive identity.
The problem is intentionally small, so the real learning sits in the surrounding details: picking the right accumulator type, iterating without an off-by-one error, and deciding how to behave when the input is empty or null. We’ll address each of these as we go.
Approach
The classic solution uses a single pass over the array with a running accumulator. Here are the steps:
- Declare an integer variable
sumand initialize it to0. - Loop from index
0up tonumbers.length - 1, visiting every element exactly once. - On each iteration, add
numbers[i]tosum. - After the loop finishes,
sumholds the total of all elements. - Return
sumto the caller.
Java Program
The full, compilable program is shown below. The sumArray helper does the actual work, and main exercises it on a short example.
public class SumOfArrayElements {
public static int sumArray(int[] numbers) {
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum = sum + numbers[i];
}
return sum;
}
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int total = sumArray(numbers);
System.out.println("Sum of all elements: " + total);
}
}Explanation of the Program
The method sumArray accepts an int[] called numbers and returns an int. Inside the method, sum starts at 0 so that an empty array produces 0 without any special case.
The for loop walks i from 0 up to but not including numbers.length. On each step, the body reads numbers[i] and adds it to the running total. Keeping the body a single statement makes the accumulator pattern easy to recognize at a glance.
Once the loop terminates, every element has been visited exactly once and sum is returned. In main, we build a sample array, call sumArray, and print the result with System.out.println.
Step-by-Step Trace
Let’s run sumArray on the input {4, 7, 2, 9, 1}, where the expected answer is 23. The table below shows one row per loop iteration.
| Iteration | i | numbers[i] | sum (before) | sum (after) |
|---|---|---|---|---|
| 1 | 0 | 4 | 0 | 4 |
| 2 | 1 | 7 | 4 | 11 |
| 3 | 2 | 2 | 11 | 13 |
| 4 | 3 | 9 | 13 | 22 |
| 5 | 4 | 1 | 22 | 23 |
At the end of iteration i, sum holds the total of numbers[0..i]. This loop invariant is what guarantees the final value equals the sum of the entire array.
Examples
Example 1: All Positive Integers
The simplest case: every element is positive, so the running total climbs monotonically from 0 to the final result.
int[] numbers = {5, 15, 25, 35};
int total = sumArray(numbers);
System.out.println(total);
// Output: 80Example 2: Mixed Positive and Negative Values
Negative values simply subtract from the accumulator. The same loop works without a single change.
int[] numbers = {-5, 10, -3, 8, 2};
int total = sumArray(numbers);
System.out.println(total);
// Output: 12Example 3: Using the Enhanced for Loop
When the index is not needed, the enhanced for loop makes the intent crisper. The behavior is identical to the indexed version.
public static int sumArray(int[] numbers) {
int sum = 0;
for (int value : numbers) {
sum += value;
}
return sum;
}Common Mistakes to Avoid
A few predictable missteps turn this five-line algorithm into a bug. Watch for the ones below.
- Seeding sum with numbers[0] and still starting at i = 0 – double-counts the first element and returns a result that is
numbers[0]too large. Either keepsum = 0and start ati = 0, or seed withnumbers[0]and start the loop ati = 1. - Using int for very large arrays – summing millions of large positives silently exceeds
Integer.MAX_VALUEand wraps to a negative result. Widen the accumulator tolongwhen the input is not strictly bounded. - Off-by-one in the loop bound – writing
i <= numbers.lengththrowsArrayIndexOutOfBoundsExceptionon the final iteration. The correct bound isi < numbers.length. - Silently returning 0 on null – treating a
nullarray as empty hides a programming error from the caller. ThrowIllegalArgumentExceptionso the mistake surfaces at the call site. - Mutating the input to carry the running total – overwriting
numbers[i]with the running sum destroys the caller’s data. Keep the accumulator as a separate local variable.
Edge Cases to Test
Before you ship, make sure the implementation behaves on every boundary input a reviewer is likely to ask about:
- Empty array
- Single-element array
- All zeros
- All negative elements
- Mixed positive and negative values
- Values near
Integer.MAX_VALUEcausing overflow - Null array reference
- Very large arrays stressing throughput
Additional Considerations
The time complexity is O(n), where n is the length of the array, because every element is read exactly once. The space complexity is O(1) since the accumulator is a single primitive and no auxiliary data structures are allocated.
Pay particular attention to overflow when the array may contain values close to Integer.MAX_VALUE. Even two such elements overflow an int accumulator on their first addition, so a long accumulator is the safe default for any array whose contents are not strictly bounded.
If the method sits on a hot path, prefer the indexed for loop over Arrays.stream(numbers).sum(). The stream version is clearer but adds the overhead of a Spliterator and extra method dispatches. For readability on cold paths, the stream is perfectly fine.
Interview Follow-up Questions
Once the base solution works, an interviewer will almost certainly push on one of these variants. Each hint points at the approach, not the full code.
- How do you prevent integer overflow when every element can be close to
Integer.MAX_VALUE? – widen the accumulator tolongand castnumbers[i]at read time; the extra 32 bits absorb any realistic sum. - What if you need the sum of a specific sub-range
[l, r]many times? – precompute a prefix-sum array once, then answer each query inO(1)asprefix[r + 1] - prefix[l]. - What if the input arrives as a stream of unknown length? – keep a running total; the loop body is identical, and termination comes from end-of-stream rather than
array.length. - What if the array has billions of elements and does not fit in memory? – partition the input across workers, sum each partition independently, then add the partition sums. The partition step is embarrassingly parallel.
- What if elements can be updated between queries and you still need fast range sums? – use a Fenwick tree (binary indexed tree) so point updates and prefix-sum queries both run in
O(log n).
Conclusion
Summing an array is a one-pass accumulator pattern, but the choices around it (accumulator width, null handling, loop bounds, and overflow safety) are the same ones that separate solid production code from a snippet that only works on textbook inputs. Walk through the trace until the invariant feels obvious, then stretch yourself with the follow-up questions.
You can learn more about array problems and related interview patterns here: Arrays.



