TheAlgorithms/Java · error · IllegalArgumentException

Input n must be non-negative

Error message

Input n must be non-negative

What it means

fibMemo(int n) computes the nth Fibonacci number using top-down memoization. Negative indices have no mathematical meaning in this sequence, so n < 0 is rejected with IllegalArgumentException. The method caches results in a static HashMap for subsequent calls.

Source

Thrown at src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java:36

 * </ul>
 * * @author Varun Upadhyay (https://github.com/varunu28)
 */
public final class Fibonacci {
    private Fibonacci() {
    }

    static final Map<Integer, Integer> CACHE = new HashMap<>();

    /**
     * This method finds the nth fibonacci number using memoization technique
     *
     * @param n The input n for which we have to determine the fibonacci number
     * Outputs the nth fibonacci number
     * @throws IllegalArgumentException if n is negative
     */
    public static int fibMemo(int n) {
        if (n < 0) {
            throw new IllegalArgumentException("Input n must be non-negative");
        }
        if (CACHE.containsKey(n)) {
            return CACHE.get(n);
        }

        int f;

        if (n <= 1) {
            f = n;
        } else {
            f = fibMemo(n - 1) + fibMemo(n - 2);
            CACHE.put(n, f);
        }
        return f;
    }

    /**
     * This method finds the nth fibonacci number using bottom up

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Validate n >= 0 before calling fibMemo.
  2. Clamp the input: use Math.max(0, n) if a default of fib(0)=0 is acceptable.
  3. Review the calling code's loop bounds and index arithmetic.

Example fix

// before
int r = Fibonacci.fibMemo(userInput); // throws if userInput < 0

// after
if (n < 0) throw new IllegalArgumentException("Index must be >= 0");
int r = Fibonacci.fibMemo(n);
Defensive patterns

Strategy: validation

Validate before calling

if (n < 0) {
    throw new IllegalArgumentException("Index must be non-negative, got: " + n);
}
int result = Fibonacci.fibMemo(n);

Type guard

static boolean isValidFibIndex(int n) {
    return n >= 0;
}

Try / catch

try {
    result = Fibonacci.fibMemo(n);
} catch (IllegalArgumentException e) {
    result = 0; // default for invalid index
}

Prevention

When it happens

Trigger: Calling Fibonacci.fibMemo(-1) or any negative n, often from user input parsed without bounds checking or from an off-by-one loop that produces a negative index.

Common situations: Parsing user-supplied indices without validation; array index arithmetic that underflows; incorrect decrement in a loop feeding n.

Related errors


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