TheAlgorithms/Java · error · IllegalArgumentException

Array must be non-empty.

Error message

Array must be non-empty.

What it means

Thrown by FindMax.findMax(int[] array) when the input array has length 0. The method iterates from index 1 comparing against array[0] as the initial max; without at least one element there is no valid starting maximum. The guard prevents an ArrayIndexOutOfBoundsException at array[0].

Source

Thrown at src/main/java/com/thealgorithms/maths/FindMax.java:17

package com.thealgorithms.maths;

public final class FindMax {
    private FindMax() {
    }

    /**
     * @brief finds the maximum value stored in the input array
     *
     * @param array the input array
     * @exception IllegalArgumentException input array is empty
     * @return the maximum value stored in the input array
     */
    public static int findMax(final int[] array) {
        int n = array.length;
        if (n == 0) {
            throw new IllegalArgumentException("Array must be non-empty.");
        }
        int max = array[0];
        for (int i = 1; i < n; i++) {
            if (array[i] > max) {
                max = array[i];
            }
        }
        return max;
    }
}

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Check array.length > 0 before calling findMax.
  2. Return an Optional<Integer> from your own wrapper to handle the empty case gracefully.
  3. Ensure upstream data sources never produce empty arrays, or handle the empty case explicitly in business logic.

Example fix

// before
int max = FindMax.findMax(data);

// after
if (data.length == 0) {
    throw new IllegalStateException("Cannot find max of empty dataset");
}
int max = FindMax.findMax(data);
Defensive patterns

Strategy: validation

Validate before calling

if (array == null || array.length == 0) {
    throw new IllegalArgumentException("Array must be non-empty");
}
int max = FindMax.findMax(array);

Type guard

static boolean isNonEmpty(int[] array) {
    return array != null && array.length > 0;
}

Try / catch

try {
    int max = FindMax.findMax(array);
} catch (IllegalArgumentException e) {
    // array was empty; provide default or rethrow
}

Prevention

When it happens

Trigger: Calling findMax(new int[0]) or passing any zero-length array. Also triggered if an upstream operation (filter, split, sublist) produces an empty array that is forwarded without a size check.

Common situations: Processing collections or streams that may legitimately be empty after filtering. Receiving arrays from external APIs, file parsing, or database queries that return zero rows. Test fixtures that forget to populate the array.

Related errors


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