TheAlgorithms/Java · error · IllegalArgumentException

Input array must not be null.

Error message

Input array must not be null.

What it means

Thrown by LibrarySort.sort(int[]) when array == null. Library sort inserts elements into a gap-based structure, which requires a concrete array reference. The guard converts a potential NullPointerException into a clear IllegalArgumentException before allocating the internal buffers.

Source

Thrown at src/main/java/com/thealgorithms/sorts/LibrarySort.java:36

 */
public final class LibrarySort {

    private static final int GAP_FACTOR = 2;

    private LibrarySort() {
        // Utility class
    }

    /**
     * Sorts an array using the Library Sort algorithm.
     *
     * @param array the array to sort (must not be null)
     * @return the sorted array
     * @throws IllegalArgumentException if {@code array} is {@code null}
     */
    public static int[] sort(final int[] array) {
        if (array == null) {
            throw new IllegalArgumentException("Input array must not be null.");
        }
        if (array.length <= 1) {
            return array;
        }

        final int n = array.length;
        final int capacity = GAP_FACTOR * n;
        final int[] data = new int[capacity];
        final boolean[] occupied = new boolean[capacity];

        final int mid = capacity / 2;
        data[mid] = array[0];
        occupied[mid] = true;

        int filled = 1;
        int nextToInsert = 1;
        int round = 0;
        while (nextToInsert < n) {

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Null-check the array before calling sort() and return an empty array.
  2. Initialize int[] fields to empty arrays rather than null.
  3. Use Optional<int[]> or @NonNull annotations to make nullability explicit.

Example fix

// before
int[] sorted = LibrarySort.sort(arr);

// after
if (arr == null) return new int[0];
int[] sorted = LibrarySort.sort(arr);
Defensive patterns

Strategy: validation

Validate before calling

if (array == null) return new int[0];

Type guard

public static boolean isSortable(int[] array) { return array != null; }

Prevention

When it happens

Trigger: Calling sort(null); passing an uninitialized int[] field; forwarding a null from a parser or Map.get().

Common situations: Optional data left null; data source returning null for missing input; null used as an 'absent' marker.

Related errors


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