What is ArrayUtils.addFirst in Java?

addFirst() is a static method of the ArrayUtils class that copies the elements of the given array to a new array and adds the new element to the beginning of the new array. So, the output of this method would be a new array containing the element to be added followed by all the elements of the array.

If the input array is null, a new one-element array with the given element is returned. 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

Applying the addFirst function will result in the following array: [10, 1,2,3,4,5]

Example 2

  • array = null
  • element: 10

Applying the addFirst function will result in the following array: [10]

ArrayUtils is defined in the Apache Commons Lang package. Apache Commons Lang can be added to the Maven project by adding 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[] addFirst(final int[] array, final int element)

Parameters

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

Returns

This method returns a new array containing the element to be added, followed by all the elements of the 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};
System.out.print("Original Array - ");
for(int i: array){
System.out.print(i + " ");
}
int elementToAdd = 10;
int[] result = ArrayUtils.addFirst(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 
Modified Array after adding element - 10 1 2 3 4 5

Free Resources