Sum Array Elements in Java
Problem
The sum of an array is the total you get from adding every one of its elements together.
Given an array of integers, find the sum of its elements.
Java Program
public class SumArrayElements {
public static void main(String[] args) {
int[] arr = {6, 2, 9, 4, 7};
int sum = 0;
for (int num : arr) {
sum += num; // add each element into the running total
}
System.out.println("Sum: " + sum);
}
}Output
Core Logic
A single pass through the array, adding each value into a running total, is all it takes.
- 1
sumstarts at0, the correct starting point for an empty total. - 2A for-each loop visits every element of
arrin turn. - 3Each element is added into
sumwithsum += num. - 4After the full pass,
sumholds the total of every element.
[6, 2, 9, 4, 7], sum accumulates to 6, 8, 17, 21, 28 across the pass.Key Point: Starting sum at 0 matters — the identity value for addition — since starting from any other number would throw off every total that follows.
Why: Each element is visited once and added into a single running total, regardless of array size.
Key Concepts
Approach 2: Java 8
import java.util.Arrays;
public class SumArrayElementsStream {
public static void main(String[] args) {
int[] arr = {6, 2, 9, 4, 7};
// sum() reduces the stream down to the total of every element
int sum = Arrays.stream(arr).sum();
System.out.println("Sum: " + sum);
}
}
Output
Core Logic
A stream can reduce the whole array down to its total in one call, without a running total variable.
- 1
Arrays.stream(arr)converts theint[]into anIntStream. - 2
.sum()reduces the stream down to the total of every element. - 3The result is a plain
int, ready to print directly.
Arrays.stream(new int[]{6, 2, 9, 4, 7}).sum() reduces the array down to 28.Key Point: sum() reads as a direct statement of intent — 'the sum of this stream' — compared to the loop version's explicit accumulation step by step.
Why: sum() still visits every element once internally, and reduces down to a single int without allocating any extra storage.