Java – Add Element to Ending of Array

Java Array, by default, does not support to add or remove an element. Therefore, to add an element to the ending of given array, create a new array with the original size + 1, and then assign the elements in the original array, and the new element to the new array.

We can use Arrays.copyOf(int[] original, int newLength) function to create a new array with original array contents and new length.

Examples

In the following example, we take an integer array and add an element to the ending of this array.

Main.java

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int arr[] = {2, 4, 6};
        int element = 8;

        int newArr[] = Arrays.copyOf(arr, arr.length + 1); 
        newArr[arr.length] = element;

        System.out.println("Original  : " + Arrays.toString(arr));
        System.out.println("New Array : " + Arrays.toString(newArr));
    }
}

Output

Original  : [2, 4, 6]
New Array : [2, 4, 6, 8]
ADVERTISEMENT

Conclusion

In this Java Tutorial, we learned how to add an element to the ending of an array with examples.