{"record":{"id":"dfaa27f8c4327234","repo":"TheAlgorithms/Java","slug":"n-must-be-non-negative-dfaa27","errorCode":null,"errorMessage":"n must be non-negative.","messagePattern":"n must be non-negative\\.","errorType":"exception","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/maths/SumOfOddNumbers.java","lineNumber":21,"sourceCode":"/**\n * This program calculates the sum of the first n odd numbers.\n *\n * https://www.cuemath.com/algebra/sum-of-odd-numbers/\n */\n\npublic final class SumOfOddNumbers {\n    private SumOfOddNumbers() {\n    }\n\n    /**\n     * Calculate sum of the first n odd numbers\n     *\n     * @param n the number of odd numbers to sum\n     * @return sum of the first n odd numbers\n     */\n    public static int sumOfFirstNOddNumbers(final int n) {\n        if (n < 0) {\n            throw new IllegalArgumentException(\"n must be non-negative.\");\n        }\n        return n * n;\n    }\n}\n","sourceCodeStart":3,"sourceCodeEnd":26,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/maths/SumOfOddNumbers.java#L3-L26","documentation":"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.","triggerScenarios":"Call sumOfFirstNOddNumbers(-1) or pass a count derived from user input or a size computation that underflowed.","commonSituations":"Parsing a user-supplied count without validation, off-by-one in loop bounds, or an empty collection whose size was decremented.","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)."],"exampleFix":"// before\nint s = SumOfOddNumbers.sumOfFirstNOddNumbers(n);\n\n// after\nint s = SumOfOddNumbers.sumOfFirstNOddNumbers(Math.max(0, n));","handlingStrategy":"validation","validationCode":"if (n < 0) throw new IllegalArgumentException(\"n must be >= 0\");\nint s = SumOfOddNumbers.sumOfFirstNOddNumbers(n);","typeGuard":null,"tryCatchPattern":null,"preventionTips":["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'."],"tags":["math","odd-numbers","input-validation","argument-validation"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}