TheAlgorithms/Java · error · IllegalArgumentException

Negative numbers are not allowed.

Error message

Negative numbers are not allowed.

What it means

Thrown by EvilNumber.isEvilNumber when number < 0. An Evil number has an even count of 1-bits in its binary representation; the bit-counting is defined for the non-negative integer representation. Negative Java ints have a two's-complement representation whose bit count is not meaningful for this classification, so the library rejects negatives before counting.

Source

Thrown at src/main/java/com/thealgorithms/maths/EvilNumber.java:33

    // Function to count number of one bits in a number using bitwise operators
    private static int countOneBits(int number) {
        int oneBitCounter = 0;
        while (number > 0) {
            oneBitCounter += number & 1; // increment count if last bit is 1
            number >>= 1; // right shift to next bit
        }
        return oneBitCounter;
    }

    /**
     * Check either {@code number} is an Evil number or Odious number
     *
     * @param number the number
     * @return {@code true} if {@code number} is an Evil number, otherwise false (in case of of Odious number)
     */
    public static boolean isEvilNumber(int number) {
        if (number < 0) {
            throw new IllegalArgumentException("Negative numbers are not allowed.");
        }

        int noOfOneBits = countOneBits(number);
        return noOfOneBits % 2 == 0;
    }
}

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Pass a non-negative integer (>= 0) such as isEvilNumber(15).
  2. Validate at the caller: if (number < 0) reject.
  3. Use Math.abs only if negative input is truly equivalent in your domain (note: this changes the bit pattern, so prefer rejecting).

Example fix

// before
boolean e = EvilNumber.isEvilNumber(-1);

// after
boolean e = EvilNumber.isEvilNumber(15);
Defensive patterns

Strategy: validation

Validate before calling

if (number < 0) {
    throw new IllegalArgumentException("Evil number check requires >= 0");
}
EvilNumber.isEvilNumber(number);

Type guard

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

Prevention

When it happens

Trigger: Calling isEvilNumber(-1), isEvilNumber(-15), or passing an unvalidated value. The guard fires before countOneBits is invoked.

Common situations: User input accepting negative numbers; arithmetic that underflows; default values; using the method in a loop that includes negative indices.

Related errors


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