{"record":{"id":"803d8805917f158d","repo":"TheAlgorithms/Java","slug":"input-cannot-be-negative","errorCode":null,"errorMessage":"Input cannot be negative","messagePattern":"Input cannot be negative","errorType":"validation","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/bitmanipulation/HighestSetBit.java","lineNumber":39,"sourceCode":"\n    private HighestSetBit() {\n    }\n\n    /**\n     * Finds the highest (most significant) set bit in the given integer.\n     * The method returns the position (index) of the highest set bit as an {@link Optional}.\n     *\n     * - If the number is 0, no bits are set, and the method returns {@link Optional#empty()}.\n     * - If the number is negative, the method throws {@link IllegalArgumentException}.\n     *\n     * @param num The input integer for which the highest set bit is to be found. It must be non-negative.\n     * @return An {@link Optional} containing the index of the highest set bit (zero-based).\n     *         Returns {@link Optional#empty()} if the number is 0.\n     * @throws IllegalArgumentException if the input number is negative.\n     */\n    public static Optional<Integer> findHighestSetBit(int num) {\n        if (num < 0) {\n            throw new IllegalArgumentException(\"Input cannot be negative\");\n        }\n\n        if (num == 0) {\n            return Optional.empty();\n        }\n\n        int position = 0;\n        while (num > 0) {\n            num >>= 1;\n            position++;\n        }\n\n        return Optional.of(position - 1); // Subtract 1 to convert to zero-based index\n    }\n}\n","sourceCodeStart":21,"sourceCodeEnd":55,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/bitmanipulation/HighestSetBit.java#L21-L55","documentation":"Thrown by HighestSetBit.findHighestSetBit(int) when the input integer is negative. The method locates the index of the highest (most-significant) set bit in a non-negative value, returning Optional.empty() for 0. Negative values are rejected because in Java's two's complement encoding bit 31 is always set, which makes the 'highest set bit' result meaningless and surprising, so the library mandates non-negative input.","triggerScenarios":"Calling findHighestSetBit(num) with any value where num < 0 (e.g. -1, -42, Integer.MIN_VALUE). This includes results of subtractions that underflow past zero and ints read from a byte stream that are logically unsigned but Java interprets as signed.","commonSituations":"Reading a magnitude from a network/byte buffer where the sign bit is set; arithmetic like a - b where b > a; converting a long mask to int without checking range; off-by-one loops that decrement past zero.","solutions":["Guard the call: only invoke findHighestSetBit when num >= 0.","If the value is logically unsigned, convert with Integer.toUnsignedLong and operate on that, or mask the sign bit consciously.","If you genuinely need the highest set bit of a negative int, reconsider — in two's complement it is always bit 31, so handle that case explicitly instead of relying on this method."],"exampleFix":"// before\nint pos = HighestSetBit.findHighestSetBit(a - b).orElse(-1);\n\n// after\nint diff = a - b;\nint pos = diff >= 0 ? HighestSetBit.findHighestSetBit(diff).orElse(-1) : -1;","handlingStrategy":"validation","validationCode":"if (num < 0) {\n    throw new IllegalArgumentException(\"num must be non-negative, got \" + num);\n}\nOptional<Integer> result = HighestSetBit.findHighestSetBit(num);","typeGuard":"// Java has no runtime type guard; use a static helper\nstatic boolean isFindable(int num) { return num >= 0; }","tryCatchPattern":"try {\n    Optional<Integer> pos = HighestSetBit.findHighestSetBit(num);\n} catch (IllegalArgumentException e) {\n    // handle negative input: log and use a sentinel\n    pos = Optional.empty();\n}","preventionTips":["Treat unsigned quantities read from bytes as long (Integer.toUnsignedLong) to avoid accidental negatives.","Wrap any subtraction feeding this method in a >= 0 check.","Unit-test boundary values 0, 1, and Integer.MAX_VALUE alongside negatives."],"tags":["bit-manipulation","java","validation","illegalargumentexception"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}