0

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; } }

8th May 2020, 4:06 PM
Mouad Taoussi
Mouad Taoussi - avatar
4 odpowiedzi
+ 1
it works! Thank you Jaykrishna! you saved my life;
8th May 2020, 4:20 PM
Mouad Taoussi
Mouad Taoussi - avatar
+ 1
Thank you Martin Taylor! this is helpful!
8th May 2020, 5:35 PM
Mouad Taoussi
Mouad Taoussi - avatar
10th May 2020, 10:52 AM
narayanaprasad
narayanaprasad - avatar
0
arr[arr.length+1] will give you error indexoutofbounds. .. public static int[] addElement(int[] array, int elem){ int[] arr = new int[array.length +1]; for(int i = 0,k = 0; i < array.length; i++) arr[k++] = array[i]; arr[k] = elem; return arr; } I think, this works check one... If not reply.....
8th May 2020, 4:15 PM
Jayakrishna 🇮🇳