An array sum folds each element into an accumulator; the chosen numeric range and empty-input result are part of its contract.
Sum an integer array
Task
Return the sum of an integer array. Assume the sum fits in an int.
Example solution
static int sum(int[] values) {
int total = 0;
for (int value : values) {
total += value;
}
return total;
}Check your work
{1, 2, 3} returns 6. An empty array returns 0. Decide separately how your program should handle a null input; this version assumes a non-null array.
Define the range before optimizing
The existing method assumes the sum fits in int. That is a precondition, not a check implemented by ordinary addition. A pair of large positive values can wrap to a negative result. Decide whether the application should reject overflow with Math.addExact or accumulate into a wider long result.
An empty array returns zero because zero is the additive identity. Null is not an empty array. Treating the two as equivalent can hide missing data, so either reject null explicitly or document an intentional default at the caller’s boundary.
Negative elements are valid under this arithmetic contract. A method that silently skips them is no longer a sum. Test positive-only, negative-only, mixed-sign and zero-filled arrays before reusing the calculation for a ledger.
Compare against an independent expectation
A test should compare the returned result with a known total and fail when the values differ. Printing a total and visually accepting it is too easy to miss in a larger test run. Include a case that reaches the chosen maximum boundary and a case that exceeds it under a rejecting policy.
The loop visits each element once, so it performs O(n) work and uses O(1) extra storage. Sorting before summing adds work without changing the arithmetic result under exact integer addition. Converting the array to a list adds allocation unless another part of the application actually needs that representation.
A parallel sum needs a defined combination rule and adds task overhead. For floating-point values, regrouping additions can change rounding results; that is a different numeric contract. See decimal calculations when exact business rounding is required.
Common Mistakes
Check empty inputs and invalid values before applying this operation to application data. State whether a method edits shared state or returns a separate value.
