Average Value of an Array in Java
Finding the average of an array is one of the first tasks people solve when learning algorithms. The solution takes two steps: add up all the elements, then divide the sum by the number of elements. In this lesson we will walk through the classic solution with a loop, the modern one-liner with the Stream API, and the cases that are easy to get wrong: integer division and empty arrays.
1. Finding the Average Using a Loop
Let's look at how to implement an algorithm for calculating the average value of the elements in an array.
First we use a loop to iterate through all the array elements and compute their total sum. Then we divide that sum by the array’s length to get the arithmetic average:
public class AverageExample {
public static void main(String[] args) {
double[] nums = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
for (double d : nums) {
result += d;
}
System.out.println("Average value: " + result / nums.length);
}
} Program output:
Average value: 12.3 The time complexity of this algorithm is O(n): every element of the array is visited exactly once.
2. Average of an Array with the Stream API
Since Java 8, the same task can be solved in a single line with the average() method from the Stream API:
import java.util.Arrays;
public class AverageStreamExample {
public static void main(String[] args) {
double[] nums = {10.1, 11.2, 12.3, 13.4, 14.5};
double average = Arrays.stream(nums)
.average()
.orElse(0);
System.out.println("Average value: " + average);
}
} Note that average() returns an OptionalDouble, not a double. This is how the Stream API handles the empty-array case: the average of zero elements is undefined, so for an empty array average() returns an empty OptionalDouble. The orElse(0) call supplies a default value for that situation. The loop-based solution in the same scenario would quietly compute 0.0 / 0 and print NaN.
3. Integer Arrays: Division and Overflow
With an int[] array, the straightforward solution produces a surprising result:
int[] nums = {1, 2, 3, 4};
int sum = 0;
for (int n : nums) {
sum += n;
}
System.out.println(sum / nums.length); // 2 — wrong!
System.out.println((double) sum / nums.length); // 2.5 — correct Both operands, sum and nums.length, are of type int, so Java performs integer division and the fractional part is discarded. To get the exact result, cast one of the operands to double.
Important
The expression sum / nums.length with integer operands drops the fractional part before the result is ever assigned to a double variable. Cast one of the operands of the division to double, not the result: (double) sum / nums.length.
The second issue is overflow: the sum of many large int values can exceed the int range, silently producing an incorrect result with no error at all. It is safer to accumulate the sum in a long variable, or to use the Stream API — for an IntStream, the average() method accumulates the sum in a long:
int[] big = {Integer.MAX_VALUE, Integer.MAX_VALUE};
double average = Arrays.stream(big)
.average()
.orElse(0);
System.out.println(average); // 2.147483647E9 — no overflow 4. What's Next: Sorting Algorithms
Calculating the average value is the first of the standard algorithms covered in this section. Next, we will move on to array sorting algorithms implemented in Java.
There are many sorting algorithms and their variations: bubble sort, selection sort, insertion sort, radix sort, quick sort, heap sort, merge sort, Shell sort, and topological sort. In the following lessons we will implement some of these algorithms step by step.
Frequently Asked Questions
How do I find the average of an array in Java in one line?
Use the Stream API: Arrays.stream(nums).average().orElse(0). The average() method works for int[], long[], and double[] arrays and returns an OptionalDouble.
Why does the array {1, 2, 3, 4} give 2 instead of 2.5?
Because both the sum and the array length are of type int, and dividing two int values in Java is integer division: the fractional part is discarded. Cast one of the operands to double: (double) sum / nums.length.
What does average() return for an empty array?
An empty OptionalDouble, because the average of zero elements is undefined. You provide a default value with orElse(). A loop-based solution over an empty double[] array would compute 0.0 / 0 and return NaN.
Is there a built-in average() method in Math or Arrays?
No. Neither java.lang.Math nor java.util.Arrays has such a method. The standard way is Arrays.stream(nums).average(), i.e. the average() method of the primitive streams IntStream, LongStream, and DoubleStream.
Comments