Skip to content

Java Reverse Array Example

Java reverse array example shows how to reverse an array in Java with a temporary array, without a temporary array, using Collections, and using Apache commons library.

How to reverse an array in Java?

There are several ways in which you can reverse an array in Java as given below.

1) Reverse an array using the Collections and Arrays classes

If you want to reverse an object array, we can use the reverse method of the Collections class and the asList method of the Arrays class.

The asList method of the Arrays class converts an array to a List that is backed by the original array. The reverse method reverses a List as given below.

Output

Note: This approach does not work for an array of primitive values, for example, an array of int.

2) Using the second array

We can also use a second array and a for loop as given below.

Output

3) Using a for loop and swapping elements

You can also avoid using the second array and do the in-place swapping as given below.

Output

Basically, we are swapping the first half of the elements of an array with the second half to reverse it.

4) Using Apache Commons

If you are using the Apache Commons library, you can use the static reverse method of the ArrayUtils class. The reverse method has been overloaded for all the primitive types as well as for an Object type.

a) int array

Output

b) String array

Output

This example is a part of the Java Array tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.