import java.util.Arrays;
import java.lang.String;
public class Adding_elements_Array{
static void add(int []arr,int element,int index,int size){
for(int i=size-1;i>=index;i++){
arr[i+1]=arr[i];
}
arr[index]=element;
}
public static void main(String[] args){
int []arr={1,2,3,4,5,6};
int size=6;
int element=7,index=2;
add(arr,element,index,size);
size+=1;
System.out.println(Arrays.toString(arr));
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6
at Adding_elements_Array.add(Adding_elements_Array.java:6)
at Adding_elements_Array.main(Adding_elements_Array.java:14)
The above code is giving me this exception but the size of the array is 6 I tried many things but it is giving me the same exception I am using the same logic to code in C++ and the program in C++ is working but in java, it is not working. When I am giving the size 5 it is working but the program replaced 3 not moved it to the following index.
The output must be:
[1,2,7,3,4,5,6]