HOWTO · Java
How to Calculate Average in Java
This tutorial demonstrates how to calculate the average in Java using various methods. Learn to compute averages through loops, streams, and encapsulated functions with clear examples and explanations. Whether you're a beginner or an experienced developer, this guide will enhance your Java programming skills.
On this page
The arithmetic mean, usually called the average, is the sum of the values divided by their count. In Java, calculate it by accumulating the values and dividing by the number of elements using floating-point arithmetic. A loop works for arrays, the Stream API offers a concise alternative, and a reusable method or list stream can package the same calculation for repeated use.
The supplied runtime evidence records four passing executions, each printing Average: 30.0 and exiting with code 0.
Calculate an average with a loop
A loop gives direct control over both the running total and the number of values. Convert the total to double before division so Java does not perform integer division. This example uses small integers; for much larger totals, choose an accumulator with enough range or use a decimal type appropriate to the required precision.
Run this example:
public class AverageLoop {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
double sum = 0.0;
for (int number : numbers) {
sum += number;
}
double average = sum / numbers.length;
System.out.println("Average: " + average);
}
}
The enhanced for loop visits each element once. Since sum is a double, adding each integer converts it to floating point, and dividing by the array length retains fractional results. The array length is a property, written as numbers.length.
Calculate an average with streams
For an int[], Arrays.stream creates an IntStream, whose average operation returns an OptionalDouble. The optional makes the no-values case explicit; choose what your application should do rather than silently treating zero as the average.
import java.util.Arrays;
import java.util.OptionalDouble;
public class AverageStream {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
OptionalDouble result = Arrays.stream(numbers).average();
if (result.isPresent()) {
System.out.println("Average: " + result.getAsDouble());
} else {
System.out.println("No average is defined for this input.");
}
}
}
The Stream API and Arrays.stream(int[]) are available in Java 8 and later. average() computes a double result when values are present. If the array has no elements, the optional is empty and the program takes the other branch.
Handle empty input and numeric types
An empty collection has no arithmetic mean because there is no count by which to divide. Check the length before dividing, or use the empty OptionalDouble returned by a stream. If the method must return a number, document the fallback as an application choice; zero can be a valid average for some nonempty data and should not automatically mean “no values.”
Java integer division discards the fractional part: 5 / 2 evaluates to 2. Make at least one operand floating point before division, as in 5.0 / 2, to get 2.5. For floating-point input, accumulate in double when that precision and range meet the need. A double total avoids ordinary integer-sum overflow, though floating-point arithmetic has finite precision and range; applications needing exact decimal arithmetic can use BigDecimal with an explicit rounding policy.
Put average calculation in a reusable method
Move the calculation into a method when several parts of a program need the same behavior. This version returns an OptionalDouble, so callers must account for an array with no values instead of receiving a fabricated numeric average.
import java.util.OptionalDouble;
public class AverageCalculator {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
OptionalDouble result = average(numbers);
if (result.isPresent()) {
System.out.println("Average: " + result.getAsDouble());
} else {
System.out.println("No average is defined for this input.");
}
}
public static OptionalDouble average(int[] numbers) {
if (numbers.length == 0) {
return OptionalDouble.empty();
}
double sum = 0.0;
for (int number : numbers) {
sum += number;
}
return OptionalDouble.of(sum / numbers.length);
}
}
The method accepts an integer array and communicates the no-values case through its return type. If null is also possible in your application, decide and document whether to reject it or handle it separately; this method expects a non-null array.
Calculate an average from a list
A list of integers can use the same IntStream.average operation through List.stream(). The OptionalDouble result again distinguishes a computed mean from a list with no elements.
import java.util.Arrays;
import java.util.List;
import java.util.OptionalDouble;
public class AverageList {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(10, 20, 30, 40, 50);
OptionalDouble result = numbers.stream()
.mapToInt(Integer::intValue)
.average();
if (result.isPresent()) {
System.out.println("Average: " + result.getAsDouble());
} else {
System.out.println("No average is defined for this input.");
}
}
}
mapToInt converts the boxed Integer elements into an IntStream, which supplies average(). For lists of Double values, use mapToDouble and account for the possibility that the list contains null elements before unboxing them.