Adding a new element to the array in Java
i have implemented this code below for add new element to the array but it return this error below Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: index 6 out of bounds for length 5 at ArrayMethods.addElement(ArrayMethods.java.29) at Main.main(Main.java:17) This is the code public class ArrayMethods { public static int[] addElement(int[] array, int elem){ // Something goes here... // Init output array int[] arr = new int[array.length +1]; // Copy the elements of the array // to an output array and the extra one for(int i = 0,k = 0; i < array.length; i++){ arr[k++] = array[i]; // Check if array filled for add new element if (arr.length-1 == array.length){ arr[arr.length+1] = elem; } else{ continue; } } // Return to the output return arr; } }