Java ProgramsArraysSum Array Elements

Sum Array Elements in Java

beginner·  Arrays  ·  Array

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.

Input
[6, 2, 9, 4, 7]
Output
Sum: 28

Java Program

Java
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

Sum: 28

Core Logic

A single pass through the array, adding each value into a running total, is all it takes.

How It Works
  1. 1sum starts at 0, the correct starting point for an empty total.
  2. 2A for-each loop visits every element of arr in turn.
  3. 3Each element is added into sum with sum += num.
  4. 4After the full pass, sum holds the total of every element.
For [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.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

Why: Each element is visited once and added into a single running total, regardless of array size.

Key Concepts

for-each looprunning total

Approach 2: Java 8

Java
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

Sum: 28

Core Logic

A stream can reduce the whole array down to its total in one call, without a running total variable.

How It Works
  1. 1Arrays.stream(arr) converts the int[] into an IntStream.
  2. 2.sum() reduces the stream down to the total of every element.
  3. 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.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

Why: sum() still visits every element once internally, and reduces down to a single int without allocating any extra storage.

Key Concepts

StreamIntStreamsum()

Related Programs