Calculate Average of Numbers in Java
Problem
An average is a sum divided by a count — when there are only a few fixed values to average, that's a single expression, not something that needs a loop.
Given four individual numbers, calculate their average.
Java Program
public class CalculateAverageOfNumbers {
public static void main(String[] args) {
double a = 10.0;
double b = 20.0;
double c = 30.0;
double d = 40.0;
double average = (a + b + c + d) / 4; // sum divided by count
System.out.println("Average: " + average);
}
}Output
Core Logic
Adding all four numbers together and dividing by the count of numbers gives the average directly, in a single expression.
- 1
a,b,c, anddhold10.0,20.0,30.0, and40.0. - 2
(a + b + c + d) / 4evaluates to25.0. - 3The result is stored in
averageand printed with a label.
10.0, 20.0, 30.0, and 40.0, (10.0 + 20.0 + 30.0 + 40.0) / 4 gives 25.0.Key Point: This works well for a small, fixed set of values known in advance — averaging a variable-sized or user-supplied collection of numbers instead calls for an array and a loop, which is exactly what a separate array-based average page covers.
Key Concepts
Approach 2: Java 8
import java.util.stream.DoubleStream;
public class CalculateAverageOfNumbersStream {
public static void main(String[] args) {
double a = 10.0;
double b = 20.0;
double c = 30.0;
double d = 40.0;
// average() returns an OptionalDouble, since an empty stream has no average
double average = DoubleStream.of(a, b, c, d).average().getAsDouble();
System.out.println("Average: " + average);
}
}
Output
Core Logic
DoubleStream.of() treats the four fixed values as a tiny stream and its built-in average() computes the mean directly, without writing the sum-divided-by-count expression by hand.
- 1
DoubleStream.of(a, b, c, d)wraps the four values in a stream, without needing an array to hold them first. - 2
.average()returns anOptionalDouble, since averaging an empty stream would have no defined result. - 3
.getAsDouble()unwraps that Optional to get the actual average — safe here since the stream always has exactly four elements.
DoubleStream.of(10.0, 20.0, 30.0, 40.0).average() produces an OptionalDouble holding 25.0, the same result the manual sum-and-divide expression gives.Key Point: OptionalDouble is what makes average() honest about the empty-stream case — calling .getAsDouble() without checking would throw NoSuchElementException if the stream had no elements at all.