{"record":{"id":"8558ecf484d257df","repo":"TheAlgorithms/Java","slug":"position-must-be-between-0-and-array-length","errorCode":null,"errorMessage":"Position must be between 0 and {array.length}","messagePattern":"Position must be between 0 and (.+?)","errorType":"exception","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/others/InsertDeleteInArray.java","lineNumber":60,"sourceCode":"     * Creates a new array with size = original array size + 1.\n     * Elements at positions &lt;= insertPos retain their positions,\n     * while elements at positions &gt; insertPos are shifted right by one position.\n     * </p>\n     *\n     * @param array    the original array\n     * @param element  the element to be inserted\n     * @param position the index at which the element should be inserted (0-based)\n     * @return a new array with the element inserted at the specified position\n     * @throws IllegalArgumentException if position is negative or greater than\n     *                                  array length\n     * @throws IllegalArgumentException if array is null\n     */\n    public static int[] insertElement(int[] array, int element, int position) {\n        if (array == null) {\n            throw new IllegalArgumentException(\"Array cannot be null\");\n        }\n        if (position < 0 || position > array.length) {\n            throw new IllegalArgumentException(\"Position must be between 0 and \" + array.length);\n        }\n\n        int[] newArray = new int[array.length + 1];\n\n        // Copy elements before insertion position\n        System.arraycopy(array, 0, newArray, 0, position);\n\n        // Insert the new element\n        newArray[position] = element;\n\n        // Copy remaining elements after insertion position\n        System.arraycopy(array, position, newArray, position + 1, array.length - position);\n\n        return newArray;\n    }\n\n    /**\n     * Deletes an element at the specified position from the array.","sourceCodeStart":42,"sourceCodeEnd":78,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java#L42-L78","documentation":"Thrown by InsertDeleteInArray.insertElement when the requested insertion position is outside the valid inclusive range [0, array.length]. The library enforces this so that System.arraycopy never reads out of bounds and the returned array stays well-formed. The message appends the actual array length so the caller sees the accepted upper bound.","triggerScenarios":"Calling insertElement(array, element, position) with position < 0 or position > array.length. Inserting at exactly array.length IS allowed (appends); anything beyond it is rejected.","commonSituations":"Off-by-one from treating the valid insert slot as array.length-1 (forgetting append is legal); passing a position computed from a different/older array length; user-supplied index parsed from input without clamping; negative index coming from an arithmetic underflow.","solutions":["Clamp or validate position to [0, array.length] before calling insertElement.","If you meant to append, pass position = array.length explicitly.","Re-derive the index from the same array instance you pass in, not a stale copy.","Sanitize external/user input (round, bound, reject) before it reaches this method."],"exampleFix":"// before\nint[] out = InsertDeleteInArray.insertElement(arr, val, arr.length + 1); // throws\n\n// after\nint pos = Math.max(0, Math.min(position, arr.length));\nint[] out = InsertDeleteInArray.insertElement(arr, val, pos);","handlingStrategy":"validation","validationCode":"public static int safePosition(int[] array, int requested) {\n    if (array == null) throw new IllegalArgumentException(\"array is null\");\n    return Math.max(0, Math.min(requested, array.length));\n}\n// usage:\nInsertDeleteInArray.insertElement(arr, val, safePosition(arr, requested));","typeGuard":"public static boolean isValidInsertPosition(int[] array, int position) {\n    return array != null && position >= 0 && position <= array.length;\n}","tryCatchPattern":"try {\n    out = InsertDeleteInArray.insertElement(arr, val, pos);\n} catch (IllegalArgumentException e) {\n    // log pos and arr.length, fall back to appending at the end\n    out = InsertDeleteInArray.insertElement(arr, val, arr.length);\n}","preventionTips":["Remember insert allows position == array.length (append) but nothing higher.","Compute the index from the exact array instance you pass in.","Bound user-supplied indices to [0, array.length] before calling."],"tags":["validation","array","input-validation","off-by-one"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}