2 ways : append to an Array in Java

In this tutorial, I will be sharing different ways to append an element to an Array in Java. After the creation of the Array, its size can not be changed. The different ways to append an element to an Array are as follow:

1. Creating new Array
2. Using ArrayList

Read Also:  Array interview questions

1. Creating new Array

We will create a newArray, greater than the size of the givenArray. In the below example we are adding a single element to the end of the Array.

1. If the size of the givenArray is n then the size of the newArray will be n+1.

2. Copy the elements from the givenArray to the newArray. We will be using Arrays.copyOf method.

Note: Arrays.copyOf(givenArray, newSize) is used to create a new Array of size newSize.

3. Insert(add) the new element at the end of the Array.


import java.util.*;
public class JavaHungry {
    public static void main(String args[]) { 
        // Initialize givenArray 
        int[] num = {2,4,6,8,10}; 
 
        // Print the givenArray
        System.out.println("Given array is : "+Arrays.toString(num)); 
 
        /* Using Arrays.copyOf(int[],int) method
        to create an Array of new size */
        num = Arrays.copyOf(num, num.length+1); 
 
        // Calculate the new length of the array
        int length = num.length; 
 
        /* Store the new element at the end of 
        the Array */
        num[length - 1] = 12;
 
        // Print the new Array
        System.out.println("New array is : "+Arrays.toString(num));
    }
}

Output:
Given array is : [2, 4, 6, 8, 10]
New array is : [2, 4, 6, 8, 10, 12]


2. Using ArrayList

1. Create an ArrayList from the givenArray by using the asList() method.
2. Add the element to the ArrayList using the add() method.
3. Convert the ArrayList to Array using the toArray() method.


import java.util.*;
public class JavaHungry {
    public static void main(String args[]) {
        // Initialize givenArray
        Integer[] num = {3,6,9,12,15}; 
 
        // Print the givenArray
        System.out.println("Given array is : "+Arrays.toString(num)); 
 
        /* Convert Array to ArrayList using
        Arrays.asList() method */
        List<Integer> arrlistObj =  
                    new ArrayList<Integer>(Arrays.asList(num)); 
 
        // Add new element to the ArrayList
        arrlistObj.add(18); 
 
        // Convert the ArrayList to Array 
        num = arrlistObj.toArray(num); 
 
        // Print the new Array
        System.out.println("New array is : "+Arrays.toString(num));
    }
}

Output:
Given array is : [3, 6, 9, 12, 15]
New array is : [3, 6, 9, 12, 15, 18]


That's all for today, please mention in comments in case you have any questions related to append an element to an Array in java.

Reference:
Arrays.copyOf Java doc

About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry