Java ProgramsBasics & I/OCalculate Average of Numbers

Calculate Average of Numbers in Java

beginner·  Basics & I/O  ·  Arithmetic

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.

Input
10.0, 20.0, 30.0, 40.0
Output
Average: 25.0

Java Program

Java
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

Average: 25.0

Core Logic

Adding all four numbers together and dividing by the count of numbers gives the average directly, in a single expression.

How It Works
  1. 1a, b, c, and d hold 10.0, 20.0, 30.0, and 40.0.
  2. 2(a + b + c + d) / 4 evaluates to 25.0.
  3. 3The result is stored in average and printed with a label.
For 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

doublearithmetic expression

Approach 2: Java 8

Java
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

Average: 25.0

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.

How It Works
  1. 1DoubleStream.of(a, b, c, d) wraps the four values in a stream, without needing an array to hold them first.
  2. 2.average() returns an OptionalDouble, since averaging an empty stream would have no defined result.
  3. 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.

Key Concepts

DoubleStreamaverage()OptionalDouble

Related Programs