This post will discuss how to add new elements to an array in Java.

We know that the size of an array can’t be modified once it is created. There is no way to resize the fixed-size arrays in Java to accommodate additional element(s).

If we need a dynamic array-based data structure, the recommended solution is to use an ArrayList. An ArrayList is a resizable-array implementation of the List interface. This class provides methods to manipulate the size of the array easily. As elements are added to the ArrayList, its capacity grows automatically. The capacity is the size of the array used to store the elements in the list.

But if you insist on using arrays, you have to instantiate a new array to accommodate the additional element. We can do this with any of the following methods:

1. Using List

The idea is to convert our array into a list, then append the specified element at the end of this list, and then use the method List.toArray() method to returns an array containing all the elements in our list. This is demonstrated below:

Download  Run Code

Output:

[1, 2, 3, 4, 5]

2. Using System.arraycopy() method

The idea is to allocate a new array of size one greater than the original array. Then call the System.arraycopy() method, which copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.

Download  Run Code

Output:

[1, 2, 3, 4, 5]

3. Using Arrays.copyOf() method

We can also use Arrays.copyOf() to allocate the larger array for accommodating the new element. It internally uses System.arraycopy() but provides a much simpler signature.

Download  Run Code

Output:

[1, 2, 3, 4, 5]

4. Using Apache Commons Lang

Another good alternative is to leverage Apache Commons ArrayUtils class add() method designed specifically for this purpose. Note that this also internally calls System.arraycopy().

Download Code

Output:

[1, 2, 3, 4, 5]

That’s all about adding new elements to an array in Java.