TheAlgorithms/Java · error · IllegalArgumentException

Input must be non-negative!

Error message

Input must be non-negative!

What it means

Thrown by JacobsthalNumber.jacobsthal(int n) when n is negative. The Jacobsthal sequence is defined for non-negative indices (J(0)=0, J(1)=1, J(n)=J(n-1)+2*J(n-2)). The method uses an iterative loop from i=2 to n, so a negative n would skip the loop entirely but the guard prevents semantically invalid input. The error uses an exclamation mark ('non-negative!') which differs in style from other messages.

Source

Thrown at src/main/java/com/thealgorithms/maths/JacobsthalNumber.java:26

 *
 * @see <a href="https://en.wikipedia.org/wiki/Jacobsthal_number">
 *     Wikipedia: Jacobsthal Number</a>
 */
public final class JacobsthalNumber {

    private JacobsthalNumber() {
        // Utility class
    }

    /**
     * Calculates the nth term of the Jacobsthal Sequence.
     *
     * @param n the index of the sequence (must be non-negative)
     * @return the nth term of the Jacobsthal Sequence
     */
    public static long jacobsthal(final int n) {
        if (n < 0) {
            throw new IllegalArgumentException("Input must be non-negative!");
        }
        if (n == 0) {
            return 0;
        }
        if (n == 1) {
            return 1;
        }
        long a = 0;
        long b = 1;
        long result = 0;
        for (int i = 2; i <= n; i++) {
            result = b + 2 * a;
            a = b;
            b = result;
        }
        return result;
    }
}

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Ensure n >= 0 before calling jacobsthal().
  2. Clamp or reject negative indices at the input boundary.
  3. Wrap in try-catch(IllegalArgumentException) for defensive handling of untrusted input.

Example fix

// before
long result = JacobsthalNumber.jacobsthal(n);

// after
if (n < 0) {
    throw new IllegalArgumentException("Index must be non-negative: " + n);
}
long result = JacobsthalNumber.jacobsthal(n);
Defensive patterns

Strategy: validation

Validate before calling

if (n < 0) {
    throw new IllegalArgumentException("Index must be non-negative: " + n);
}
long result = JacobsthalNumber.jacobsthal(n);

Type guard

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

Try / catch

try {
    long result = JacobsthalNumber.jacobsthal(n);
} catch (IllegalArgumentException e) {
    // n was negative; handle invalid index
}

Prevention

When it happens

Trigger: Calling jacobsthal(-1), jacobsthal(-10), or any negative int. The check fires before the base-case returns (n==0 returns 0, n==1 returns 1).

Common situations: User input or computed indices that go negative. Off-by-one errors in loops that decrement past zero. Recursive or formula-based callers that produce negative indices.

Related errors


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