This post will discuss how to insert an element into an array at the specified index in Java. The insertion should shift the element currently at that index and any subsequent elements to the right by one position.

We know that unlike an ArrayList, arrays in Java are fixed-size and non-dynamic. Therefore, the insertion of an element at the specified position in an array is not feasible if the array is full. This post provides an overview of some of the available alternatives to accomplish this.

1. Naive solution

We can also write our own routine for this simple task. The idea is to declare a new array with one more element, populate it with relevant values from the old array and a specified element at its correct position.

Download  Run Code

Output:

[1, 2, 3, 4, 5]

 
We can even do this in a single loop.

Download  Run Code

Output:

[1, 2, 3, 4, 5]

2. Using System.arraycopy() method

We can replace the above solution with two calls to System.arraycopy(), which can efficiently copy an array from the specified source array, beginning at the specified position, to the specified position in the destination array.

Download  Run Code

Output:

[1, 2, 3, 4, 5]

3. Using List

The idea is to convert the array into a list and call the add() method on it, which inserts the specified element at the specified position. Finally, after inserting, we convert the list back to the array. This is demonstrated below in Java 8 and above using Stream.

Download  Run Code

Output:

[1, 2, 3, 4, 5]

4. Using Java 8

In Java 8 and above, we can do something like:

Download  Run Code

Output:

[1, 2, 3, 4, 5]

5. Using Apache Commons Lang

We can also leverage Apache Commons Lang’s ArrayUtils class, which offers the insert() method. It internally uses System.arraycopy() method.

Download Code

That’s all about inserting an element into an array at a specific index in Java.