TheAlgorithms/Java · error · IllegalArgumentException

Key must not be null.

Error message

Key must not be null.

What it means

Thrown by FibonacciSearch.find(T[], T) when key == null. The search compares elements using Comparable.compareTo, which cannot meaningfully compare against null and would throw NullPointerException internally. The guard converts this into a clear precondition failure.

Source

Thrown at src/main/java/com/thealgorithms/searches/FibonacciSearch.java:39

    /**
     * Finds the index of the specified key in a sorted array using Fibonacci search.
     *
     * @param array The sorted array to search.
     * @param key The element to search for.
     * @param <T> The type of the elements in the array, which must be comparable.
     * @throws IllegalArgumentException if the input array is not sorted or empty, or if the key is null.
     * @return The index of the key if found, otherwise -1.
     */
    @Override
    public <T extends Comparable<T>> int find(T[] array, T key) {
        if (array.length == 0) {
            throw new IllegalArgumentException("Input array must not be empty.");
        }
        if (!isSorted(array)) {
            throw new IllegalArgumentException("Input array must be sorted.");
        }
        if (key == null) {
            throw new IllegalArgumentException("Key must not be null.");
        }

        int fibMinus1 = 1;
        int fibMinus2 = 0;
        int fibNumber = fibMinus1 + fibMinus2;
        int n = array.length;

        while (fibNumber < n) {
            fibMinus2 = fibMinus1;
            fibMinus1 = fibNumber;
            fibNumber = fibMinus2 + fibMinus1;
        }

        int offset = -1;

        while (fibNumber > 1) {
            int i = Math.min(offset + fibMinus2, n - 1);

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Null-check the key before calling find() and decide on a -1 or empty result per your contract.
  2. Use Optional or default sentinel values instead of null for the search key.
  3. Annotate the key parameter with @NonNull and enable static null analysis.

Example fix

// before
int idx = new FibonacciSearch().find(arr, key);

// after
if (key == null) return -1;
int idx = new FibonacciSearch().find(arr, key);
Defensive patterns

Strategy: validation

Validate before calling

if (key == null) return -1;

Type guard

public static boolean isSearchableKey(Object key) { return key != null; }

Prevention

When it happens

Trigger: Calling find(arr, null); passing a key obtained from a Map.get() that returned null; using a nullable reference without null-checking.

Common situations: Lookups keyed by optional/user input where the field was never set; deserialized DTOs with null fields; chaining methods that may return null.

Related errors


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