This post will discuss how to print the contents of an array in reverse order in Java.

1. Print array in reverse order

A simple solution to print the array contents in reverse order is using a simple for loop. The loop starts at the end of the array, prints the current element, and decrement the index by 1 at every iteration.

Download  Run Code

Output:

5
4
3
2
1

 
Here’s a version using Java 8 streams:

Download  Run Code

Output:

5
4
3
2
1

2. In-place Reverse Array

If you need to reverse an array in-place, you can use any of the following methods:

a. Using For loop

The idea is to swap items starting from both ends of the array until they cross each other. This can be easily done using a for loop:

Download  Run Code

Output:

[5, 4, 3, 2, 1]

 
The above solution uses two indices, one for each end of the array. The code can be easily modified to use only a single index:

Download  Run Code

Output:

[5, 4, 3, 2, 1]

b. Using Apache Commons Lang Library

Another good alternative to reverse the order of an array is using Apache Commons Lang ArrayUtils.add() method, which is overloaded for all primitives types and object arrays.

Download Code

Output:

[5, 4, 3, 2, 1]

c. Using Guava

With Guava, you can call the Ints.asList() method to get a fixed-size list backed by the specified array. Then call the Collections.reverse() method to reverse the order of the elements in the list.

Download Code

Output:

[5, 4, 3, 2, 1]

3. Create a Reversed Copy

If you don’t need to modify the original array, the following solution creates a reversed copy of it. The idea is to create a new array of the same size as the original array. Then fill the new arrays with the elements of the original array in reverse order using a loop.

Download  Run Code

Output:

[5, 4, 3, 2, 1]

 
Here’s a version using Java 8 streams:

Download  Run Code

Output:

[5, 4, 3, 2, 1]

That’s all about printing contents of an array in reverse order in Java.