Title: Sum of Positive Elements in an Array
In this guide, you will learn how to compute the sum of positive elements in a Java integer array. This is a classic warm-up problem for array traversal, and it shows up in interviews as a stepping stone to harder questions like maximum subarray sum and subarray with target sum. We will walk through the problem statement, build a clean algorithm, write a compilable Java program, trace it on a small input, and finish with the edge cases and interview follow-ups a strong candidate is expected to raise.
Let us explore how to solve this cleanly, keep the code O(n), and avoid the small off-by-one and sign-check mistakes that often cost points in a real interview.
Understanding the Problem
You are given an integer array numbers. Return the sum of all elements that are strictly greater than zero. Zero and negative values are ignored and contribute nothing to the sum. If the array is empty, the sum is 0. If the array reference is null, the method should raise an exception rather than silently return a misleading value.
The input size can be anything from zero up to the maximum Java array length, and individual elements can span the full int range from Integer.MIN_VALUE to Integer.MAX_VALUE. The output type matters: if many large positive values are present, a plain int accumulator can overflow silently, so we will discuss when to switch to long.
Approach
The algorithm is a single linear scan. We keep a running accumulator sum and add each element that passes the > 0 test. There is no need to sort, no need for extra memory, and the work is O(n) regardless of input shape.
- Validate the input: if
numbersisnull, throwIllegalArgumentExceptionso the problem surfaces at the call site rather than hiding behind a bogus zero. - Initialize
sum = 0. This is the correct identity for addition, and it is also the right answer for an empty array. - Iterate from
i = 0tonumbers.length - 1with a standardforloop. - For each element, check
numbers[i] > 0. Use a strict greater-than so zero is correctly skipped. - If the element is positive, add it to
sumwithsum += numbers[i]. - After the loop ends, return
sum.
Java Program
public class SumOfPositiveElements {
public static int sumPositive(int[] numbers) {
if (numbers == null) {
throw new IllegalArgumentException("Array must not be null");
}
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] > 0) {
sum += numbers[i];
}
}
return sum;
}
public static void main(String[] args) {
int[] numbers = {4, -2, 7, -5, 9, 0, 3};
int result = sumPositive(numbers);
System.out.println("Sum of positive elements: " + result);
}
}Explanation of the Program
The sumPositive method takes an int[] and returns an int. The first line is a defensive check: a null array is a programmer error, not a value we can meaningfully sum, so we throw IllegalArgumentException. This fails loudly at the call site instead of letting a NullPointerException surface deeper in the stack.
We then initialize sum to 0, which is the identity for addition. For an empty array the for loop never executes, so the method correctly returns 0 without a special case.
The loop walks every index from 0 to numbers.length - 1. The condition numbers[i] > 0 is strict, so a 0 value in the array is correctly skipped. Each positive value is accumulated with sum += numbers[i], and the final return sum hands the result back to the caller. The main method shows the API in use with a representative mixed input.
Step-by-Step Trace
Let us trace the algorithm on the input [4, -2, 7, -5, 9]. The expected output is 20, since the positive values are 4, 7, and 9.
| Iteration | numbers[i] | sum (before) | numbers[i] > 0? | sum (after) |
|---|---|---|---|---|
| 1 | 4 | 0 | yes | 4 |
| 2 | -2 | 4 | no | 4 |
| 3 | 7 | 4 | yes | 11 |
| 4 | -5 | 11 | no | 11 |
| 5 | 9 | 11 | yes | 20 |
At the end of iteration i, sum holds the sum of all positive values in numbers[0..i]. This is the loop invariant, and once the loop terminates at i = numbers.length - 1, sum is the answer for the full array.
Examples
Example 1: All Positive Values
When every element is positive, the method just sums the whole array.
int[] numbers = {1, 2, 3, 4, 5};
// Output: Sum of positive elements: 15Example 2: All Negative Values
When no element is positive, the method returns 0. This is the correct answer, not an error, because the sum over an empty set of positives is 0.
int[] numbers = {-1, -2, -3, -4};
// Output: Sum of positive elements: 0Example 3: Mixed Values With a Zero
The zero is skipped because 0 > 0 is false. Only 10, 20, and 3 contribute, giving 33.
int[] numbers = {10, 0, -5, 20, -15, 3};
// Output: Sum of positive elements: 33Common Mistakes to Avoid
These are the slip-ups that most often land on this problem in interviews and in production code. Each one is a logic error, not a syntax error, so the compiler will not catch them for you.
- Using >= instead of > – treats
0as positive, so an input like[0, 0, 0]still returns0, but[-1, 0, 1]wrongly includes the zero in intermediate reasoning and confuses the invariant. Use strictnumbers[i] > 0. - Returning the first positive instead of the sum – a
return numbers[i]inside theifshort-circuits the loop and gives a single value, not a sum. Thereturnbelongs after the loop, outside theif. - Initializing sum to numbers[0] – mirrors the “find max” idiom but is wrong here. If
numbers[0]is negative, you have already added it to the sum before checking its sign. Always startsum = 0. - Using int for very large inputs – a million elements near
Integer.MAX_VALUE / 2will overflow anintaccumulator silently, flipping to a large negative number. Promotesumtolongwhen input size and element magnitude can produce more than2^31 - 1. - Returning 0 for a null array – hides a programmer error behind a plausible-looking answer. Throw
IllegalArgumentExceptionso the caller sees the bug immediately.
Edge Cases to Test
Walk through this list before writing a single assertion. An interviewer specifically watches for the candidate who enumerates these unprompted.
- Empty array
- Single positive element
- Single negative element
- All negative elements
- All positive elements
- Array containing zeros only
- Mixed positives, negatives, and zeros
- Integer.MAX_VALUE present (overflow risk)
- Null array reference
Additional Considerations
The time complexity is O(n), where n is numbers.length. Each element is read exactly once and the per-element work is constant. The space complexity is O(1) because the only extra storage is the sum accumulator and the loop index i; no auxiliary array or collection is allocated.
The overflow risk is the main non-obvious hazard. For a defensive production variant, change the signature to return long and declare long sum = 0L. The addition sum += numbers[i] then widens numbers[i] from int to long implicitly, and the result can safely hold any sum reachable from an int[].
If the array is already sorted in ascending order, the problem is easier: scan from the right until you hit a non-positive element, then stop. That cuts the work in half on average but keeps the asymptotic complexity at O(n). Streams give a one-liner with Arrays.stream(numbers).filter(x -> x > 0).sum(), which is readable but allocates an IntStream pipeline and is slower than the manual loop for small inputs.
Interview Follow-up Questions
The base problem usually lasts five minutes in a real interview. Expect follow-ups like these, which probe depth around data types, scaling, and alternative formulations.
- What if the sum can exceed Integer.MAX_VALUE? – switch the accumulator and return type to
longso the implicitinttolongwidening on each add prevents overflow. - What if you also need the count of positives? – track a second variable
countinside the same loop and return a small record or a two-element array; the extra work is still O(n). - What if you must do this in place without any extra variables? – fold the running sum into
numbers[0]as you iterate, trading array mutation for the O(1) extra space the interviewer wants to see justified. - What if the array arrives as a stream of unknown length? – maintain a running
sumon each incoming value; termination comes from end-of-stream rather than an index bound, and the loop body is unchanged. - What if the array has billions of elements across multiple machines? – partition the input, compute the positive-sum of each partition independently, then add the partial sums. The map step is embarrassingly parallel and the reduce step is a single pass over the partition count.
Conclusion
Summing the positive elements of an array is a one-pass problem with a tight O(n) solution, but the details are what interviewers reward: a strict > 0 check so zero is handled correctly, a sum = 0 initial value that falls out of the identity-element reasoning, a null-check that fails loudly, and an awareness of when int overflow forces a jump to long.
Try adapting the code to count positives, sum only even-indexed positives, or sum values that pass a user-supplied predicate; each variation reuses the same loop skeleton and reinforces the invariant. You can learn more about array algorithms in Java: Arrays category.



