How to Find Array Average in Java
The Challenge
Calculate the average (mean) of all elements in an array!
Solutions
Method 1: Using Loop
int[] numbers = {10, 20, 30, 40, 50};
int sum = 0;
for (int num : numbers) {
sum += num;
}
double average = (double) sum / numbers.length;
System.out.println("Average: " + average);
// Output: Average: 30.0Method 2: Using Java 8 Streams
import java.util.Arrays;
int[] numbers = {10, 20, 30, 40, 50};
double average = Arrays.stream(numbers).average().orElse(0.0);
System.out.println("Average: " + average);
// Output: Average: 30.0Did You Know?
The average() method returns an OptionalDouble to handle empty arrays gracefully. Use orElse() to provide a default value!
Watch Out!
Remember to cast to double to avoid integer division: (double) sum / length
Real-World Use Cases
- Statistics: Calculate mean of dataset
- Grading: Calculate student average
- Analytics: Average user engagement
- Performance: Average response time
›Short versionOpen if you only have a minute.
- Average is the sum divided by the length.
- int division drops the fraction. 3 / 2 is 1.
- Cast before dividing: (double) sum / length.
- An empty array has length 0. Do not divide.
Array average
Compute the total divided by the number of elements, keeping a fractional result.
Working approach
- Sum in a long.
- Reject an empty array.
- Divide a double by the length.
Walk the sample
- Values 2, 4, 7
- Sum 13, length 3
- 13.0 / 3 is about 4.333
The trap
sum / length uses integer division whenever both sides are integral types, even if the variable you assign to is a double. The fraction is already gone.
static double average(int[] values) {
if (values.length == 0) {
throw new IllegalArgumentException("empty array");
}
long sum = 0;
for (int value : values) {
sum += value;
}
return (double) sum / values.length;
}What is the average of {1, 2} if the sum and the length are both ints?
The sum is 3. 3 / 2 in int arithmetic is 1. Assigning 1 to a double stores 1.0.
(double) sum / length is 1.5. Check length before the division so an empty array does not throw ArithmeticException by accident.
Time O(n), space O(1).
Easy to get wrong
- Dividing two ints and storing the truncated result in a double.
- Dividing by length without checking for 0.