Average Array Elements in Java
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.
Java Program
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
Core Logic
Summing every element in one pass, then dividing that total by the count, gives the average directly.
- 1
sumstarts at0and accumulates every element's value across a for-each loop, the same as summing an array. - 2
arr.lengthgives the number of elements to divide by. - 3
(double) sum / arr.lengthcastssumto adoublebefore dividing, so the result keeps any fractional part. - 4The final
averageis printed with its decimal places intact.
[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.
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
Approach 2: Java 8
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
Core Logic
A stream can compute the average directly, without manually summing and dividing.
- 1
Arrays.stream(arr)converts theint[]into anIntStream. - 2
.average()computes the mean of every element, returning it wrapped in anOptionalDouble. - 3
.getAsDouble()unwraps theOptionalDoubleinto a plaindouble.
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().
Why: average() still visits every element once internally to compute the sum and count, without allocating any extra storage.