Java ProgramsArraysAverage Array Elements

Average Array Elements in Java

beginner·  Arrays  ·  Array

Problem

The average of an array is its sum divided by the number of elements it contains.

Given an array of integers, find the average of its elements.

Input
[6, 2, 9, 4, 7]
Output
Average: 5.6

Java Program

Java
public class AverageArrayElements { public static void main(String[] args) { int[] arr = {6, 2, 9, 4, 7}; int sum = 0; for (int num : arr) { sum += num; } double average = (double) sum / arr.length; // cast before dividing to keep the fractional part System.out.println("Average: " + average); } }

Output

Average: 5.6

Core Logic

Summing every element in one pass, then dividing that total by the count, gives the average directly.

How It Works
  1. 1sum starts at 0 and accumulates every element's value across a for-each loop, the same as summing an array.
  2. 2arr.length gives the number of elements to divide by.
  3. 3(double) sum / arr.length casts sum to a double before dividing, so the result keeps any fractional part.
  4. 4The final average is printed with its decimal places intact.
For [6, 2, 9, 4, 7], the sum is 28, and dividing by 5 elements gives an average of 5.6.
💡

Key Point: Casting sum to double before dividing is essential — without it, 28 / 5 would perform integer division and truncate to 5, losing the .6.

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

Why: Each element is visited once to build the running total, and only the sum and count are kept regardless of array size.

Key Concepts

for-each looprunning totaltype casting

Approach 2: Java 8

Java
import java.util.Arrays; public class AverageArrayElementsStream { public static void main(String[] args) { int[] arr = {6, 2, 9, 4, 7}; // average() computes the mean directly, wrapped in an OptionalDouble double average = Arrays.stream(arr).average().getAsDouble(); System.out.println("Average: " + average); } }

Output

Average: 5.6

Core Logic

A stream can compute the average directly, without manually summing and dividing.

How It Works
  1. 1Arrays.stream(arr) converts the int[] into an IntStream.
  2. 2.average() computes the mean of every element, returning it wrapped in an OptionalDouble.
  3. 3.getAsDouble() unwraps the OptionalDouble into a plain double.
Arrays.stream(new int[]{6, 2, 9, 4, 7}).average() reduces the array down to 5.6.
💡

Key Point: OptionalDouble is empty if the array is empty, so calling .getAsDouble() without checking .isPresent() first would throw — the same caveat as reducing an empty stream with .max().

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

Why: average() still visits every element once internally to compute the sum and count, without allocating any extra storage.

Key Concepts

StreamIntStreamaverage()OptionalDouble

Related Programs