TheAlgorithms/Java · error · IllegalArgumentException
n must be non-negative.
Error message
n must be non-negative.
What it means
Thrown by SumOfOddNumbers.sumOfFirstNOddNumbers when n is negative. The method returns n*n (the identity that the sum of the first n odd numbers equals n^2), which is only meaningful for n >= 0; a negative count of 'first N odd numbers' is undefined.
Source
Thrown at src/main/java/com/thealgorithms/maths/SumOfOddNumbers.java:21
/**
* This program calculates the sum of the first n odd numbers.
*
* https://www.cuemath.com/algebra/sum-of-odd-numbers/
*/
public final class SumOfOddNumbers {
private SumOfOddNumbers() {
}
/**
* Calculate sum of the first n odd numbers
*
* @param n the number of odd numbers to sum
* @return sum of the first n odd numbers
*/
public static int sumOfFirstNOddNumbers(final int n) {
if (n < 0) {
throw new IllegalArgumentException("n must be non-negative.");
}
return n * n;
}
}
View on GitHub (pinned to fdfb9a395b)
Solutions
- Validate n >= 0 at the call site before invoking.
- Use Math.max(0, n) when a negative should silently map to 0.
- Sanitize the source of n (e.g., parsed CLI argument or HTTP parameter).
Example fix
// before int s = SumOfOddNumbers.sumOfFirstNOddNumbers(n); // after int s = SumOfOddNumbers.sumOfFirstNOddNumbers(Math.max(0, n));
Defensive patterns
Strategy: validation
Validate before calling
if (n < 0) throw new IllegalArgumentException("n must be >= 0");
int s = SumOfOddNumbers.sumOfFirstNOddNumbers(n); Prevention
- Treat any 'first N' API as requiring N >= 0 by default.
- Use Math.max(0, n) when a negative should silently mean 'zero odd numbers'.
When it happens
Trigger: Call sumOfFirstNOddNumbers(-1) or pass a count derived from user input or a size computation that underflowed.
Common situations: Parsing a user-supplied count without validation, off-by-one in loop bounds, or an empty collection whose size was decremented.
Related errors
- The number must be in the range [%d, %d]
- Input array must have length of at least two
- numOfTerms nonnegative.
- Input must be non-negative
- sylvester() does not accept negative numbers or zero.
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/dfaa27f8c4327234.
Report an issue: GitHub.