How to Find the Average of Array Elements in Java
Calculating an average sounds almost too simple to write an entire article about — until you hit the classic Java “gotcha” where dividing two integers silently truncates the decimal portion, giving you a wrong answer with no warning or error.
This guide shows you the correct way to compute an average in Java, explains exactly why type casting matters, and walks through several implementation styles.
Problem Statement
Given an array like {10, 20, 30, 40, 50}, the average is the sum of all elements divided by the count of elements — in this case:
150 / 5 = 30
Simple arithmetic, but Java’s handling of integer division makes this a genuinely common source of bugs for beginners.
The Integer Division Trap
Here’s the trap in action:
int sum = 17;
int count = 5;
int average = sum / count; // average = 3, NOT 3.4!
When you divide two int values in Java, the result is also an int, and any decimal portion is simply discarded (truncated, not rounded).
This is one of the most common silent bugs new Java developers introduce, precisely because the code compiles and runs without any error — it just produces a subtly wrong number.
The fix is to force at least one operand into a floating-point type before the division happens.
double average = (double) sum / count; // average = 3.4, correct!
Method 1: Classic Loop With Type Casting
public class AverageOfArray {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum = sum + numbers[i];
}
double average = (double) sum / numbers.length;
System.out.println("Average of array elements: " + average);
}
}
Output
Average of array elements: 30.0
Method 2: Enhanced For Loop
int sum = 0;
for (int num : numbers) {
sum += num;
}
double average = (double) sum / numbers.length;
Method 3: Java Streams
import java.util.Arrays;
double average = Arrays.stream(numbers)
.average()
.getAsDouble();
Stream.average() returns an OptionalDouble (because an empty stream has no meaningful average), so .getAsDouble() extracts the value.
However, be aware this throws an exception on an empty array.
A safer approach is:
double average = Arrays.stream(numbers)
.average()
.orElse(0.0);
Step-by-Step Explanation
Sum Calculation
The loop accumulates the total of all elements exactly as covered in our Sum of Array Elements article.
The Cast
(double) sum
converts the integer sum into its floating-point equivalent before the division takes place.
This is crucial.
Casting the entire expression after division:
(double) (sum / numbers.length)
does not help, because the truncation has already happened during integer division.
Division
(double) sum / numbers.length
now performs floating-point division, correctly preserving the decimal portion.
Internal Working (Memory View)
Stack
sum (int) = 150
numbers.length (int) = 5
(double) sum
↓
150.0
average (double) = 30.0
The JVM promotes the int operand to double at the bytecode level using a widening primitive conversion instruction, ensuring the subsequent division instruction operates on floating-point values.
Real-Life Analogy
Imagine splitting a restaurant bill of ₹170 among 5 friends using only whole rupee coins.
You’d naturally calculate:
170 ÷ 5 = 34
But suppose the bill is ₹173.
If you only allow whole rupees (like integer division), everyone still pays ₹34, silently losing ₹3 somewhere.
Casting to double is like allowing paise in the calculation, so the division is exact and nothing gets silently dropped.
Best Practices
- Always cast at least one operand to
double(orfloat) before dividing when computing averages. - Use
Arrays.stream(arr).average().orElse(0.0)for concise, safe stream-based averaging that handles empty arrays gracefully. - Format the output with
String.format("%.2f", average)when displaying to users, to control decimal precision. - Consider
BigDecimalif you need exact decimal precision for financial calculations, sincedoublecan introduce floating-point rounding errors.
Common Mistakes
Forgetting to Cast to double
This results in silently truncated (wrong) averages.
Casting After Division
Casting the result after division does not fix the truncation issue.
Dividing by Zero
Always check:
numbers.length > 0
before dividing when the array might be empty.
Using float Unnecessarily
double provides better precision at negligible extra cost for most use cases.
Expert Tips
Arrays.stream(arr).average()returnsOptionalDoublespecifically because an empty array has no meaningful average. Always handle that case explicitly rather than assuming a value.- For weighted averages or averages excluding certain values, streams’
.filter()composes cleanly before.average(). - If working with a
double[]array from the start, useDoubleStreaminstead ofIntStream.
Arrays.stream(doubleArray)
.average();
Comparison Table
| Approach | Handles Empty Array | Readability | Precision Control |
|---|---|---|---|
| Manual loop + cast | Manual check needed | Medium | Full control |
Streams .average() |
Returns OptionalDouble |
High | Good, via orElse() |
BigDecimal |
Manual check needed | Low (verbose) | Excellent (exact decimals) |
Frequently Asked Questions
Why does my average print as a whole number instead of a decimal?
You’re likely dividing two int values without casting one to double first, causing integer division to truncate the decimal part.
Where exactly should I place the (double) cast?
Before the division operation, on either the numerator or denominator.
Casting the final result after division does not fix the issue.
What does Arrays.stream(arr).average() return?
An OptionalDouble, since averaging an empty array has no defined value.
Use .getAsDouble() or .orElse(defaultValue) to extract the value.
How do I round the average to 2 decimal places?
Use:
String.format("%.2f", average);
or
Math.round(average * 100.0) / 100.0;
Can I compute the average of a double[] array the same way?
Yes.
You won’t need the cast trick since dividing two double values already produces a decimal result naturally.
What happens if I try to average an empty array using streams?
.average() returns an empty OptionalDouble.
Calling .getAsDouble() throws a NoSuchElementException.
Use:
.orElse(0.0)
to avoid this.
Is there a difference between average and median?
Yes.
Average (mean) sums all values and divides by the count.
Median is the middle value after sorting.
They measure different things and require different logic.
Should I use float or double for averages?
double is almost always preferred in modern Java because it provides higher precision with negligible performance cost on modern hardware.
Conclusion
Finding the average of array elements in Java is straightforward once you understand the importance of type casting.
The recommended workflow is:
- Calculate the sum of all elements.
- Cast the sum (or divisor) to
double. - Divide by the array length.
- Handle empty arrays when necessary.
Whether you use a classic loop, an enhanced for loop, or Java Streams, ensuring floating-point division happens before the calculation is the key to producing accurate results.