How to Add an Element to an Array in Java?

The array has a defined length that can not be changed by any inherent Java method. An array can store various elements in a unified variable so there is no need to declare more variables. In Java, there are no direct methods that can add an element inside an array. However, custom methods can be created to integrate new elements into an already existing array.

This write-up demonstrates several methods to add an element within an array and explains each method with suitable examples.

How to Add/Insert a New Element to an Array in Java?

An array consists of elements with a similar data type located adjacently in the memory. The array has a single dimension and stores the elements in series. The elements inside an array are arbitrarily accessible unlike that of a list. There is no inherent method in Java programming to add an element to the array.

Let us understand adding an element in the array with a visual representation of an example where 50 is added at the index position 2:

Syntax of Creating an Array

The syntax for creating an array is as follows:

data_type arr_name[] = {val1, val2, val3 ...., valn};
  • data_type represents the data type of the values.
  • arr_name[] represents the name of the array
  • val1, val2,…,valn are the values stored inside the array, which must be of the same type.

In Java programming, no intrinsic method exists that can add an element in the Array. We have to create our own methods for adding an element to any particular array. Some of the methods by which we can add an element to an array are: 

  1. Create a New Array of Bigger Length
  2. Add an Element to an Array Through ArrayList
  3. Add an Element to an Array Through Apache Common Library
  4. Add an Element to an Array Through the ArrayCopyOf() 
  5. Add an Element to an Array Through System.arraycopy()
  6. Shifting Elements to Adjust the Size of the Array

Let us discuss each method in great detail.

Method 1: Create a New Array of Bigger Length

One way to add an element to an already existing array is to make another array with all the elements as our original array. The new value is to be inserted/added at the last of the new array. Let us suppose that the size of our original array is n then the size of our updated array will be n+1 and the new element will be added to the (n+1)th position. However, this approach is not considered to be the most efficient one for adding an element inside an array. Here is a code that explains the demonstration of adding an element inside an array while creating a new array of increased length:

import java.util.Arrays; 
public class add_element{ 
public static void main(String[] args) { 
int array[] = {23,45,67,89,5}; 
int len = array.length; 
int updated_array[] = new int[len+1]; 
int val = 45; 
for(int i = 0; i<len; i++) {&nbsp;
updated_array[i] = array[i];&nbsp;
}&nbsp;
updated_array[len] = val;&nbsp;
System.out.println("The original array is : " + Arrays.toString(array));
System.out.println("Array after adding an element to it : " + Arrays.toString(updated_array));&nbsp;
}&nbsp;
}

In the above code,

  • Arrays class from java.util package is imported.
  • A public class add_element is defined.
  • An array is defined to have several integer values
  • The length function is called on the array which stores the array’s length in an integer variable len.
  • The int variable updated_array[] defines a new array with a greater size by one unit.
  • A variable val =45 is defined that is appended at the end of the array
  • A for loop iterates through each element of the original array and copies its elements to the updated array.
  • updated_array[len] = val adds val at the end of the array.
  • The updated array with an added element of 45 is printed.

Output

45 has been added at the end of the updated array:

Method 2: Add an Element to an Array Through ArrayList

There is a direct method of adding elements to an array. What we can do is convert the array into lists, add the elements, and convert them back to the array. This way, we can add the element inside an array. ArrayList has a dynamic nature which means that the size of the array list can be increased dynamically. Several elements can be added to the selected array. ArrayList acts as an intermedial structure when elements are added to the array. Here is a code that demonstrates how an element can be added to the array using an ArrayList:

import java.util.ArrayList;&nbsp;
import java.util.Arrays;&nbsp;
public class add_element {&nbsp;
public static void main(String[] args) {&nbsp;
Integer array[] = {12,34,56,88};&nbsp;System.out.println("The original array is : "+ Arrays.toString(array));
ArrayList<Integer> arrayList = new ArrayList<Integer>(Arrays.asList(array));&nbsp;
arrayList.add(64);&nbsp;
array = arrayList.toArray(array); &nbsp;
System.out.println("The updated array after adding an element to it : "+ Arrays.toString(array));&nbsp;
}&nbsp;
}

In the above code,

  • The ArrayList and the Arrays class from the java.utils package is imported.
  • A public class add_element is defined.
  • An array is defined and printed that contains different integer values. 
  • An array list is defined which is assigned the values of the previously defined array.
  • The add method is called on the arrayList which appends 64 at the end of the list.
  • The arrayList is converted back to the array using the toArray method and stored in the variable array.
  • The modified array with an appended element of 64 is printed.

Output

Here 64 is added at the end of an array. The following output displays how an element can be added to an array using an ArrayList:

Method 3: Add an Element to an Array Through Apache Common Library

Using a third-party library which is Apache Common Lang is a non-conventional way of adding an element in the array. The Apache Commons Library is based on the Java components that are frequently in use. The Apache Common Library contains the function add() which is specifically designed to enable the lengthening of an array. It is an efficient way of adding an element inside an array.

Adding the Apache Common Library in the “pom.xml” File

To add elements to an array using the Apache common library, first, create a maven project, and then add the following dependency between the opening and closing tags of dependencies. This will enable the users to avail the functionalities defined in the Apache Common Library. The dependency to integrate the Apache Common Library is as follows:

<dependency>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <groupId>org.apache.commons</groupId>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <artifactId>commons-lang3</artifactId>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <version>3.12.0</version>
&nbsp; &nbsp; </dependency>

The following code shows how an element can be added to an array using the append method from utils.Arrays given by the Apache Common Library:

package com.example;
import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;
class add_element {
&nbsp; private static <T> T[] append(T[] array, T num) {
&nbsp; &nbsp; &nbsp; return ArrayUtils.add(array, num);
&nbsp; }
&nbsp; public static void main(String[] args) {
&nbsp; &nbsp; &nbsp; Integer[] sample_array = { 12,75,20,86};
&nbsp; &nbsp; &nbsp; System.out.println("The original array is : " + Arrays.toString(sample_array));
&nbsp; &nbsp; &nbsp; sample_array = append(sample_array, 25);
&nbsp; &nbsp; &nbsp; System.out.println("The sample array with an added element is : " + Arrays.toString(sample_array));
&nbsp; }
}

In the above code,

  • The Arrays class from the java.util package is imported.
  • The ArrayUtils class is imported from Apache’s Commons Lang library and contains various functionalities to work with the arrays.
  • A java class add_element is defined.
  • The add method appends an element at the last index of the selected array.
  • A sample_array is defined which contains different integer values.
  • The sample array is printed.
  • The append() method is called on the sample_array with the num parameter equal to 25, which will insert 25 at the end of the given array.
  • The updated array with 25 appended at the last is printed.

Output

The following output displays how an element can be added inside an array using functionalities from the Apache Commons Lang:

Method 4: Add an Element to an Array Through the ArrayCopyOf()

Another method to add an element inside the Java array is to use the ArrayCopyOf() method. It allows the concise implementation of adding an element to the array. The below-stated code shows how to insert an element inside an array using ArrayCopyOf():

import java.util.Arrays;
class add_element {
&nbsp; &nbsp;public static void main( String args[] ) {
&nbsp; &nbsp; &nbsp; int[] array = { 10, 20, 30 };&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println("The original array is : "+Arrays.toString(array));
&nbsp; &nbsp; &nbsp;array = Arrays.copyOf(array, array.length + 1);
&nbsp; &nbsp; &nbsp; array[array.length - 1] = 39:
&nbsp; &nbsp; &nbsp; System.out.println("The updated array with an added element is : "+ Arrays.toString(array));
&nbsp; &nbsp; }
}

In the above code,

  • The Arrays class from the java.util package is imported.
  • A java class add_element is defined.
  • An integer array with values 10, 20, and 30 is defined and printed.
  • A new array is created that has a length greater than the original array by a unit. The actual/original array is assigned to the new array using “Arrays.copyOf()”.
  • 39 is added/inserted at the end of the provided array.
  • The modified array with an appended element is printed.

Output

The following output displays how element 39 is appended at the end of the array using the ArrayCopyOf() method in Java:

Method 5: Add an Element to an Array Through System.arraycopy()

System.arraycopy()  is one of the common methods for allocating an array of greater length to the location of the original array. The sequence in which the new array is to be updated is defined by the programmer inside the brackets of the method. The below-given code illustrates how an element can be added to an array using the System.arraycopy():

import java.util.Arrays;
class appended_array {
&nbsp; private static Integer[] add_element(Integer[] arr, int num) {
&nbsp; &nbsp; &nbsp; Integer[] array = new Integer[arr.length + 1];
&nbsp; &nbsp; &nbsp; System.arraycopy(arr, 0, array, 0, arr.length);
&nbsp; &nbsp; &nbsp; array[arr.length] = num;
&nbsp; &nbsp; &nbsp; return array;
&nbsp; }
&nbsp; public static void main(String[] args) {
&nbsp; &nbsp; &nbsp; Integer[] arr = {24,5,89,4,36};&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println("The original array is : " + Arrays.toString(arr));
&nbsp; &nbsp; &nbsp; arr = add_element(arr, 40);
&nbsp; &nbsp; &nbsp; System.out.println("The updated array after adding an element is : " + Arrays.toString(arr));
&nbsp; }
}

In the above code,

  • The Arrays class is imported from the java.utils package.
  • A class appended_array is defined which has a private static method add_element. It takes the argument arr which is the original array and a num which represents the number that is to be added at the end of an array.
  • The System.arraycopy adds the element at the last index of the array.
  • An array arr is defined which contains different integer values.
  • The add_element function takes arr and 40 as parameter values that will append 40 at the end of the array.
  • The modified array is printed.

Output

40 has been added to the original array at the end using System.arraycopy():

Method 6: Shifting Elements to Adjust the Size of the Array

This method inserts an element to a specified index in an array. The implementation of this method is a bit more complicated than the rest of the methods. The following code demonstrates how an element can be added to a specified index by shifting the elements to adjust the size of the array:

import java.util.Arrays;&nbsp;
public class add_element {&nbsp;
public static void main(String[] args) {&nbsp;
Integer array[] = {23,44,56,8,43,3};&nbsp;
int len = array.length;&nbsp;
int ind = 2;&nbsp;
Integer newArray[] = new Integer[len+1];&nbsp;
int j = 0;&nbsp;
for(int i = 0; i<newArray.length; i++) {&nbsp;
if(i==ind) {&nbsp;
newArray[i] = 58;&nbsp;
}else {&nbsp;
newArray[i] = array[j];&nbsp;
j++;&nbsp;
}&nbsp;
}&nbsp;&nbsp;System.out.println("The original array is: "+Arrays.toString(array));
newArray[ind] = 58; &nbsp;
System.out.println("The updated array with an added element is : "+Arrays.toString(newArray));&nbsp;
}&nbsp;
} &nbsp;
}

In the above code,

  • The Arrays class is imported from java.utils package.
  • A public class add_element is defined.
  • An array of type int is created and the length function retrieves the size of the array which is stored in the variable len.
  • An integer value Ind is defined which defines the index value to be 2 where the element is to be added.
  • An array newArray is created that has a length greater than the original array by 1.
  • The j element tracks the position of the original array when the values are being copied from the original array to the new array
  • The for loop iterates through each element in the new array and checks if the index value is equal to ind. If the condition is true, the element is added/inserted at the index specified; otherwise, the element of the original/given array will be copied to the new array.
  • The modified array with the element 58 being added at the index position 2 is printed.

Output

Here the number 58 is added at an index position of 2. The following output displays how an element can be added to an array by shifting its existing elements to make space for the new element to be added:

This sums up the topic of adding an element to an array in Java.

Conclusion

Various methods like using an ArrayList, add() from the Apache Common Lang, ArrayCopyOf(), and System.arraycopy can be utilized to insert/add an element to an array in Java. An element can also be added by creating an array of a greater length and adding an element at the last of the original array though this is not an effective method. To add an element somewhere between the array, the elements need to be shifted to make adjustments for the new element. This article discusses different methods to add an element to an array in Java and explains each method with their respective examples.