Advertisement
Home Data Structure Arrays Find the Average of Elements in an Array

Find the Average of Elements in an Array

2
Advertisement

Title: Find the Average of Elements in an Array

In this guide, you will learn how to find the average of elements in an array using Java. Computing the arithmetic mean of a sequence of numbers is one of the first array problems every developer writes, and it is a surprisingly good lens into how Java handles types, overflow, and integer division.

We will walk through the problem, build a complete program, trace it on a sample input, and then look at the mistakes that trip up most learners along with the follow-up questions a Java interviewer tends to ask.

Understanding the Problem

Given an array of integers, the task is to compute the arithmetic mean, that is, the sum of all elements divided by the number of elements. If the array has n elements and we call them a[0], a[1], ..., a[n-1], the answer is (a[0] + a[1] + ... + a[n-1]) / n.

The problem looks trivial, but two Java-specific pitfalls hide in the one-line formula. First, adding many int values can overflow, so the running sum should be wider than int. Second, dividing two int values performs integer division and silently drops the fractional part, so one of the operands has to be a floating-point number before the division happens.

Approach / Algorithm Steps

  1. Reject the input early if the array is null or empty, since the mean is undefined when there is nothing to average.
  2. Declare a long accumulator sum initialised to 0. Using long protects against overflow when many int values are added.
  3. Iterate over every index i from 0 to numbers.length - 1 and add numbers[i] to sum.
  4. After the loop, cast sum to double and divide by numbers.length. The cast forces floating-point division so the fractional part is preserved.
  5. Return the resulting double value.

Java Program

Java
public class ArrayAverage {
    public static double findAverage(int[] numbers) {
        if (numbers == null || numbers.length == 0) {
            throw new IllegalArgumentException("Array must not be null or empty");
        }
        long sum = 0;
        for (int i = 0; i < numbers.length; i++) {
            sum += numbers[i];
        }
        return (double) sum / numbers.length;
    }

    public static void main(String[] args) {
        int[] scores = {72, 85, 90, 68, 95};
        double average = findAverage(scores);
        System.out.println("Average: " + average);
    }
}

Explanation of the Program

The class ArrayAverage exposes a single static method, findAverage, which takes an int[] and returns a double. Returning a double is deliberate, since the average of integers is almost never an integer itself.

The method starts by validating the input. A null reference or a zero-length array has no meaningful average, so the method throws an IllegalArgumentException. Pushing the error back to the caller is almost always better than inventing a sentinel like 0.0 or Double.NaN, because sentinels get silently propagated.

The accumulator sum is a long, not an int. A Java int can only hold values up to roughly 2.1 billion, so adding together a few hundred million large int values can wrap around to a negative number without any warning. A long gives us headroom up to roughly 9.2 quintillion.

The loop walks every index and adds numbers[i] to sum. After the loop, the expression (double) sum / numbers.length casts sum to a double first. Once one operand is double, Java promotes the other operand as well and the division is floating-point. Without the cast, Java would perform integer division on long / int and truncate the result.

The main method shows a tiny driver: it builds a sample array of five test scores, calls findAverage, and prints the result. Running it prints Average: 82.0.

Step-by-Step Trace

Let us trace findAverage on the input [3, 7, 2, 8, 5]. The expected final answer is 25 / 5 = 5.0.

Iteration (i)numbers[i]sum (before)sum += numbers[i]sum (after)
0300 + 33
1733 + 710
221010 + 212
381212 + 820
452020 + 525

At the end of iteration i, sum holds the total of numbers[0..i]. After the loop exits, sum = 25 and numbers.length = 5, so (double) 25 / 5 evaluates to 5.0.

Examples

Example 1: Positive integers

A straightforward input where the mean is itself an integer.

Java
int[] nums = {10, 20, 30, 40, 50};
double avg = findAverage(nums);
System.out.println(avg);
// Output: 30.0

Example 2: Mixed positive and negative values

Negative numbers work the same way, and the fractional part survives thanks to the double cast.

Java
int[] nums = {-5, 0, 5, 10};
double avg = findAverage(nums);
System.out.println(avg);
// Output: 2.5

Example 3: Single-element array

When the array has only one element, the mean is that element itself. The loop runs exactly once, and the division by 1 leaves sum unchanged.

Java
int[] nums = {100};
double avg = findAverage(nums);
System.out.println(avg);
// Output: 100.0

Common Mistakes to Avoid

A one-line formula hides a surprising number of ways to get the wrong answer. These are the mistakes learners actually hit on this problem.

  • Integer division truncation – writing return sum / numbers.length; without casting returns an integer value, so [1, 2] gives 1.0 instead of 1.5. Cast sum to double before the division.
  • int accumulator overflow – summing many large int values into an int variable can wrap around to a negative total, so the average silently becomes nonsensical. Declare sum as long instead.
  • Returning 0.0 for an empty array – zero is a valid average of a real dataset, so callers cannot tell the difference between no data and genuine data that averages to zero. Throw IllegalArgumentException so the problem surfaces at the call site.
  • Casting after the division – writing (double)(sum / numbers.length) performs integer division first and only then widens to double, so the fractional part is already lost. Cast one operand before the / operator.
  • Using float instead of double – float has about seven significant digits of precision, which is not enough for large arrays and leads to visible rounding error. Prefer double for the return type.

Edge Cases to Test

Walk through this checklist before you call the solution done. The first few are the ones an interviewer is most likely to ask about.

  • Empty array
  • Null array reference
  • Single-element array
  • All identical elements
  • All negative elements
  • Mixed positive and negative values that cancel to zero
  • Sum close to Integer.MAX_VALUE (overflow risk)
  • Integer.MIN_VALUE present in the array

Additional Considerations

The algorithm runs in O(n) time, since every element is visited exactly once, and there is no way to do better because every element can influence the mean. The space complexity is O(1), because only the sum accumulator and the loop counter are allocated regardless of the input size.

The reason Integer.MIN_VALUE deserves its own line in the checklist is that -Integer.MIN_VALUE overflows back to Integer.MIN_VALUE in two’s-complement int arithmetic. The long accumulator sidesteps the issue for the sum itself, but any code that negates individual elements first (for example, converting to absolute values before averaging) must widen to long at the point of negation.

If the input is a double[] instead of an int[], a numerically more stable alternative is Welford’s online mean, which updates a running estimate as mean += (x - mean) / count. It avoids the risk of the running sum growing so large that adding small values loses precision, and it extends naturally to streaming inputs.

Interview Follow-up Questions

The base problem is only the opening move. Expect the interviewer to push with questions like these, each probing a different axis.

  • How would you compute the average of a stream of numbers of unknown length? – maintain a running count and a running mean, updating the mean with Welford’s formula on every new value.
  • How would you compute a running average over the last K elements only? – use a fixed-size circular buffer plus a running sum: on each new value, subtract the one leaving the window and add the new one, both in O(1).
  • How would you avoid overflow if the array contains long values near Long.MAX_VALUE? – switch to BigInteger or BigDecimal for the sum, or divide incrementally using Welford’s formula so no running total ever exceeds Long.MAX_VALUE.
  • How would you compute the average of billions of elements that do not fit in memory? – partition the input, compute the partial sum and count for each partition independently (easily parallelisable), then combine them into a single mean weighted by partition size.
  • How would you compute a weighted average given a parallel array of weights? – accumulate both weightedSum = sum(numbers[i] * weights[i]) and totalWeight = sum(weights[i]), then return weightedSum / totalWeight.

Conclusion

Finding the average of an array in Java is a one-pass loop with two important details tucked inside it: use a long accumulator to protect against overflow, and cast to double before the division to protect the fractional part. Once those two habits are in place, the same shape of code extends cleanly to streaming inputs, weighted means, and partitioned data at scale.

Try adapting the code above to return the mean of a double[] using Welford’s online update, and compare its output against the naive sum-then-divide version for very large inputs. The two approaches agree on small inputs and diverge in interesting ways on long ones.

You can learn more Array problems like this one here: Arrays.