This blog will explain how to add an element to an array in Java. So let’s get started!
Adding elements to a Java array
In Java, you can add elements to an array:
- By creating a new array
- By using ArrayList
Now, let’s check out the stated method one by one.
Method 1: Adding Elements to array by creating a new Java array
To add elements to an array in Java, first create an array then copy the existing array elements in the newly created array. After doing so, you can add new elements to it.
In this example, firstly, we will create an integer array named numArray[ ] with the following values:
In the next step, we will create a new integer type array named newNumArray[ ] with a greater size of the existing array:
The element 77 is stored in the variable named appendValue, which we want to add:
For printing the array numArray[ ], use the System.out.println() method:
Now, copy the elements of array numArray[ ] in a newly created array newNumArray[ ] by using a for loop:
newNumArray[i] = numArray[i];
Then, insert the value that is stored in appendValue variable in the newNumArray[ ]:
Lastly, print the newNumArray elements:
The given output indicates that 77 is successfully added in the newNumArray[ ]:
Now, let’s check out the other method for adding elements to an array in Java.
Method 2: Adding Elements to an array in Java by using ArrayList
You can also utilize Java ArrayList to add elements to an array. It is considered ideal as ArrayList is a re-sizable array.
First of all, we will create an integer type array named numArray[ ] with the following values:
Print array by using the System.out.println() method:
Create an ArrayList named newNumArrayList and pass the array in it by using the aslist() method:
Add the required element in the created ArrayList with the help of the add() method:
Now, we will convert this ArrayList into an array by using the toArray() method:
Finally, print the array with the appended element:
We have provided all of the necessary information related to adding elements to an array in Java.
In Java, elements can be added to an array by using Array List or creating a new array. The best and most efficient method is utilizing the ArrayList for the mentioned purpose. To do so, convert the existing array into an ArrayList, add required elements, and then convert it to a normal array. ArrayList also takes less memory space. This blog discussed the methods of adding elements to an array in Java.