TheAlgorithms/Java · error · IllegalArgumentException

Numbers array cannot be empty or null

Error message

Numbers array cannot be empty or null

What it means

Thrown by Average.average(double[]) when the input array is null or has zero length. This guard prevents a division-by-zero (sum / numbers.length where length is 0) and a NullPointerException on the enhanced-for loop when numbers is null. The error message is shared with the int[] overload.

Source

Thrown at src/main/java/com/thealgorithms/maths/Average.java:34

    // Prevent instantiation of this utility class
    private Average() {
        throw new UnsupportedOperationException("This is a utility class and cannot be instantiated.");
    }

    /**
     * Computes the arithmetic mean of a {@code double} array.
     *
     * <p>The average is calculated as the sum of all elements divided
     * by the number of elements: {@code avg = Σ(numbers[i]) / n}.
     *
     * @param numbers a non-null, non-empty array of {@code double} values
     * @return the arithmetic mean of the given numbers
     * @throws IllegalArgumentException if {@code numbers} is {@code null} or empty
     */
    public static double average(double[] numbers) {
        if (numbers == null || numbers.length == 0) {
            throw new IllegalArgumentException("Numbers array cannot be empty or null");
        }
        double sum = 0;
        for (double number : numbers) {
            sum += number;
        }
        return sum / numbers.length;
    }

    /**
     * Computes the arithmetic mean of an {@code int} array.
     *
     * <p>The sum is accumulated in a {@code long} to prevent integer overflow
     * when processing large arrays or large values.
     *
     * @param numbers a non-null, non-empty array of {@code int} values
     * @return the arithmetic mean as a {@code long} (truncated toward zero)
     * @throws IllegalArgumentException if {@code numbers} is {@code null} or empty
     */

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Check for null or empty before calling: if (numbers != null && numbers.length > 0).
  2. Use the alternative method Average.averageStream(numbers) which returns OptionalDouble.empty() instead of throwing for null/empty input.
  3. Fix the upstream data source to ensure the array is populated before the call.

Example fix

// before
Average.average(new double[0]); // throws
Average.average(null);          // throws

// after (use the stream-based API for safe empty handling)
OptionalDouble result = Average.averageStream(numbers);
double mean = result.orElse(0.0); // or orElseThrow with domain-specific error
Defensive patterns

Strategy: validation

Validate before calling

// Check for null or empty before calling average(double[])
if (numbers == null || numbers.length == 0) {
    // handle gracefully: return default, log, or throw domain-specific error
    return 0.0;
}
double mean = Average.average(numbers);
// Or use the stream-based alternative that returns OptionalDouble:
OptionalDouble result = Average.averageStream(numbers);
double mean = result.orElse(0.0);

Type guard

static boolean hasElements(double[] arr) {
    return arr != null && arr.length > 0;
}

Prevention

When it happens

Trigger: Calling Average.average((double[]) null), Average.average(new double[0]), or passing a list that was converted to an empty array (e.g., list.stream().mapToDouble(Double::doubleValue).toArray() on an empty list).

Common situations: A collection or stream that was expected to contain elements but was empty due to a filtering condition that removed all items. A nullable field that was not initialized before being passed. JSON deserialization that produced a null array for a missing field.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/2b809579e1cdeb7a. Report an issue: GitHub.