TheAlgorithms/Java · error · IllegalArgumentException
number must be nonnegative.
Error message
number must be nonnegative.
What it means
Thrown by ReverseNumber.reverseNumber(int number) when number is negative. The method reverses decimal digits by repeatedly taking number % 10 and building the reversed value; the loop condition (number > 0) and digit extraction assume a non-negative input, so negatives are rejected up front.
Source
Thrown at src/main/java/com/thealgorithms/maths/ReverseNumber.java:18
package com.thealgorithms.maths;
/**
* @brief utility class reversing numbers
*/
public final class ReverseNumber {
private ReverseNumber() {
}
/**
* @brief reverses the input number
* @param number the input number
* @exception IllegalArgumentException number is negative
* @return the number created by reversing the order of digits of the input number
*/
public static int reverseNumber(int number) {
if (number < 0) {
throw new IllegalArgumentException("number must be nonnegative.");
}
int result = 0;
while (number > 0) {
result *= 10;
result += number % 10;
number /= 10;
}
return result;
}
}
View on GitHub (pinned to fdfb9a395b)
Solutions
- Decide on domain semantics: reject negatives upstream, or pass Math.abs(number) and reapply the sign afterwards.
- Validate number >= 0 at the input boundary.
- Fix upstream logic so only non-negative values reach the call.
Example fix
// before int r = ReverseNumber.reverseNumber(value); // after int sign = value < 0 ? -1 : 1; int r = sign * ReverseNumber.reverseNumber(Math.abs(value));
Defensive patterns
Strategy: validation
Validate before calling
int sign = number < 0 ? -1 : 1; int r = sign * ReverseNumber.reverseNumber(Math.abs(number));
Prevention
- Decide on domain semantics for negatives and apply abs() with sign reapplication if needed.
- Validate parsed integers for sign before the call.
- Document at the call site whether negatives are errors or to be abs()-ed.
When it happens
Trigger: Calling reverseNumber(-123) or any reverseNumber(number) where number < 0.
Common situations: User-supplied integer not sign-validated; result of a subtraction or signed computation fed directly; assumption that the method preserves the sign (it does not); parsed value from input that accepted negatives.
Related errors
- multiplicativePersistence() does not accept negative values
- additivePersistence() does not accept negative values
- Input parameter must not be negative!
- Input x-coordinates must be unique.
- Array should contain an even number of elements
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/593a0afaa9420ecc.
Report an issue: GitHub.