What is ArrayUtils.reverse in Java?

What is reverse() in Java?

reverse is a staticAny static member can be accessed before any objects of its class are created and without reference to any object. method of the ArrayUtils class that reverses the order of the elements in the given array. This method modifies the original array, as it is in-place in nature.

Add the Apache Commons-Lang package

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.

How to import ArrayUtils

You can import the ArrayUtils class as follows.


import org.apache.commons.lang3.ArrayUtils;

Syntax


public static void reverse(final int[] array)

Parameters

  • final int[] array: the array elements to be reversed.

Return value

The method doesn’t return anything, as the reversing of the elements is performed on the original array that is passed as an argument.

Code

Consider the following code, where we have the array:

  • array = [1,2,3,4,5]

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

The order of the elements is reversed.

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

Output


Original Array - 1 2 3 4 5 
Modified Array after reversing - 5 4 3 2 1 

Free Resources