What is ArrayUtils.add in Java?

add is a static method of the ArrayUtils class that copies the elements of the given array to a new array and appends the given element to the end of the new array.

If the input array is null, add returns a new one-element array with the given element. The component type of the new array is the same as that of the given element.

Example 1

  • array = [1,2,3,4,5]
  • element - 10

Application of the add function will result in the following array: [1,2,3,4,5,10].

Example 2

  • array = null
  • element - 10

Application of the add function will result in the following array: [10].

ArrayUtils is defined in the Apache Commons Lang package. To add Apache Commons Lang to the Maven Project, add the following dependency to the pom.xml file.

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

For other versions of the commons-lang package, refer to the Maven Repository.

You can import the ArrayUtils class as follows.

import org.apache.commons.lang3.ArrayUtils;

Syntax

public static int[] add(final int[] array, final int element)

Parameters

  • final int[] array: array of elements.
  • final int element: the element to be added at the end of the array.

Return value

add returns a new array that contains the existing elements with the new element appended at the end of the new array.

Code

import org.apache.commons.lang3.ArrayUtils;
public class Main {
public static void main(String[] args) {
int[] array = new int[]{1,2,3,4,5,2,3,2,2,4};
System.out.print("Original Array - ");
for(int i: array){
System.out.print(i + " ");
}
int elementToAdd = 100;
int[] result = ArrayUtils.add(array, elementToAdd);
System.out.print("\nModified Array after adding element - ");
for(int i: result){
System.out.print(i + " ");
}
}
}

Expected output

Original Array - 1 2 3 4 5 2 3 2 2 4 
Modified Array after adding element - 1 2 3 4 5 2 3 2 2 4 100

Free Resources