OneBite.Dev - Coding blog in a bite size

insert an element at a specific index in an array in java

Code snippet on how to insert an element at a specific index in an array in java

public static void addElementAtIndex(int[] arr, int index, int element) {
    for (int i = arr.length - 1; i > index; i--) {
        arr[i] = arr[i-1];
    }
    arr[index] = element;
}

This code adds an element at a specific index in an array of integers. The function takes three inputs, the array, the index where the element is to be added, and the element itself. To add the element, all values from the index that the element is being added up to the end of the array are shifted one position to the right. Then, the value of the element is set in the index that we want to add it to. The new size of the array is not changed as the code simply shifts elements to the right and overwrites the element that originally was at the index we specified.

java