CodeGym /Java Blog /Java Arrays /Reverse an Array in Java
Author
Pavlo Plynko
Java Developer at CodeGym

Reverse an Array in Java

Published in the Java Arrays group
Arrays are used frequently in coding and are a way of storing multiple values of the same type in one variable. There may be many reasons why a coder may want to reverse an array. It may be necessary to reverse an array, for example, when the logic of a problem needs to start with the last element. In this case, best practice is to do the reversal and then use the reversed array where necessary in the code. Even more, reversing an array is a very popular task in Java Juniors interviews.

How to Reverse an Array

There are many ways of reversing an array, and here we consider 5. For Option 1, an array is reversed using an additional array filled in ascending order from the end of the original array (descending), in Option 2 an in-place reversal is carried out where array elements at the beginning and end are swapped over, in Option 3, the reverse() method from the Collections framework is used to do the reversal, in Option 4, List.add() and List.remove() are used, and finally, in Option 5, recursion is used.Reverse an Array in Java - 1

Option 1: Reversing an Array using an Additional Array

Let us write a simple method to reverse an array using an additional array. This option uses an additional array which is filled starting with the last element of the original array in descending order, i.e. the first element is the same as the last element in the original array, the second is the same as the second from last and so on until the additional array is filled.

import java.util.Arrays;

public class ReverseArrayDemo {

   public static void main(String[] args) {
       int[] array = {7, 8, 9, 10, 11};
       System.out.println("Array : " + Arrays.toString(array)); // print array

       // Call function to get reversed array
       int[] reversedArray = reverse(array);
       System.out.println("Reversed array : " + Arrays.toString(reversedArray)); // print reversed array
   }

   // Method returns a new reversed array, based on the array which was passed to it.
   static int[] reverse(int[] array) {
       int[] newArray = new int[array.length];

       for (int i = 0; i < array.length; i++) {
           newArray[array.length - 1 - i] = array[i];
       }

       return newArray;
   }
}
In this example, we wrote a method which reverses an array and returns a new reversed array, based on the array which was passed to it. array is declared in main and then a method, reverse, is called. The argument to the method is the array. In method reverse, a new array, newArray, is created and is the same size as array, only completely empty. A for loop is used to fill in the newArray and operates over the whole length of the array. This is done by starting with the first element of an array and assigning it to the last element of newArray, then taking the second element of our array and assigning it to the second last element of newArray, and so on; newArray is filled in backwards. When the for loop is complete, newArray is completely full and is an exact reverse of the array.
Array : [7, 8, 9, 10, 11] Reversed array : [11, 10, 9, 8, 7]

Option 2: Print the Elements of an Array in Reverse Order

For this option to reverse an array, there is no need to use an additional array, and it is not converted into an array list. Instead the array elements are put into reverse order in-place. This means that they are, in fact, swapped. The first element is swapped with the last element, the second element is swapped with the second from last, and so on. A for loop is used and when this has been completed, the array will have been reversed. The code looks like this:

import java.util.Arrays;
/*
reversing an array in-place
*/
public class ReverseArrayDemo {

   public static void main(String[] args) {
       int[] array = {1, 4, 9, 16, 25};
       System.out.println("Array before reverse : " + Arrays.toString(array));

       arrayReverse(array);
       System.out.println("Array after reverse : " + Arrays.toString(array));
   }
//arrayReverse is a method that reverses array in-place
   static void arrayReverse(int[] array) {
       for (int i = 0; i < array.length / 2; i++) {
           int temp = array[i];
           array[i] = array[array.length - i - 1];
           array[array.length - i - 1] = temp;
       }
   }
}
The original array is printed out as a String using Arrays.toString(array), and then our array is passed as an argument into reverse. In the reverse method in the for loop, a variable, temp, is created and used. In the for loop the reverse order is achieved in three steps:
  1. assigning the first element to temp
  2. assigning the last element to the first element
  3. assigning temp to the last element
This is then carried out again this time for the second element and second from last element, and so on. This is done for successive elements of the array but the loop only iterates up to half the array size. Essentially the elements at opposite ends of the array are swapped. This method will run twice as fast as a method using a for loop going from 0 to size. As a result the reverse order of the array is achieved and we are shown how to print an array in reverse order and the values are printed out:
Array before reverse : [1, 4, 9, 16, 25] Array after reverse : [25, 16, 9, 4, 1]

Option 3: Using Collections.reverse()

In Java, the reverse method, which is part of the existing Collections framework, can be used to reverse an array. Let’s use it to do the reversal.

import java.util.Arrays;
import java.util.Collections;

public class ReverseArrayDemo {

   public static void main(String[] args) {
       Integer[] array = {1, 4, 9, 16, 25};
       System.out.println("Array before reverse : " + Arrays.toString(array));

       reverse(array);
       System.out.println("Array after reverse : " + Arrays.toString(array));
   }
//method that reverses an array
   static void reverse(Integer[] array) {
       Collections.reverse(Arrays.asList(array));
   }
}
In main, the array is created and filled as an Integer array with 5 numbers. It is then printed out as a list using Arrays.asList(array) and then the function, reverse, is called and array is passed as an argument into this function. In reverse, Collections.reverse is used, and this is used on the array list, Arrays.asList(array), rather than the array itself. Then in the next step we are shown how to print an array in reverse order using System.out.println, and this time each element is printed out on the same line:
Array before reverse : [1, 4, 9, 16, 25] Array after reverse : [25, 16, 9, 4, 1]

Option 4: Reverse an Array using List.add() and List.remove()

In this new option, List.add() and List.remove() are used to do the reversal. The way this works is that the array is converted to a list and the last element of the list removed and put at the beginning of the list. After the whole list has been iterated over, the new list is a reversal of the original. In the main() method, an array is created consisting of 5 numbers. Then the original state of the array is outputted to the console. This array is then put in as an argument to the method, reverse(). This method basically works by removing the last element and inserting it at the front of the array. Lastly, the new (reversed) state of the array is outputted to the console. In the reverse() method, the array is written to a List via Arrays.asList(array), in order to enable the add() and remove() methods to carry out the reversal. This method basically works by removing the last element and inserting it at the front of the array. The steps reverse() uses are as follows. It uses a for loop to carry out the reversal of the elements of the list. It does this by initialising a variable i. Initially the i is set to 0. When i = 0, the element at list.size() - 1 in list is removed, and this will always be the last element since i < list.size() - 1. Since the remove() method returns the element it has removed, this element is now added to the list at index i = 0, i.e., inserted at the beginning. The remainder of the list is then shifted to the right but the new list still has the same number of elements, i.e., size. Continuing the execution of the for loop with the next value of i, i = 1, the same set of steps is carried out so the last element is removed and put into nums at i = 1 and the list shifted to the right. This carries on until the last incremental value of i and all elements in the list have been changed. In the second for loop element of the list with index i is set to the array element with index i where i is from 0 to list.size() - 1. To summarise, the steps used are: Steps:
  1. i = 0
  2. remove element at list.size() - 1
  3. insert element, which was at list.size() - 1, at i = 0
  4. increment i
  5. repeat steps 2 to 4 (with new values for i at step 3) until the last incremental value of i is used

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ReverseArrayDemo {

   public static void main(String[] args) {
       Integer[] array = new Integer[]{1, 4, 9, 16, 25};
       System.out.println("Array before reverse : " + Arrays.toString(array));

       reverse(array);
       System.out.println("Array after reverse : " + Arrays.toString(array));
   }

   static void reverse(Integer[] array) {
       List list = new ArrayList<>(Arrays.asList(array));

       for (int i = 0; i < list.size() - 1; i++) {
           list.add(i, list.remove(list.size() - 1));
       }

       for (int i = 0; i < list.size(); i++) {
           array[i] = list.get(i);
       }
   }
}
This code gives the output:
Array before reverse : [1, 4, 9, 16, 25] Array after reverse : [25, 16, 9, 4, 1]

Option 5: Reverse an Array by Recursion

The method of recursion is used widely in coding and can be used to create an efficient method on how to reverse an array. In this option, the array is converted into a list and then the code goes into method reverse() each time removing the last element at the end of the list and the list has the removed values added to it in reversed order. As in the previous methods, an array is created consisting of 5 numbers. It is then passed as an argument into the function, reverse(). In reverse() the first thing that is done is to turn the array into a list and check on the list size. If it only has one element or is null then the method finishes and returns. If not, the first element is removed, but copied to an Integer, value. Method reverse() is then called again and the recursion begins again. When the function is entered, the same steps are carried out, a size check where, if the list is greater than 1 the next step will be to remove the first element and then do the recursion again. When the size of list is 1, reverse() returns to where it is called from and then the list has each value added to it to build it up into an exact reverse of the original list.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ReverseArrayDemo {

   public static void main(String[] args) {
       Integer[] array = new Integer[]{1, 4, 9, 16, 25};
       System.out.println("Array before reverse : " + Arrays.toString(array));

       List list = new ArrayList<>(Arrays.asList(array));
       reverse(list);
       System.out.println("Array after reverse : " + Arrays.toString(list.toArray()));
   }

   public static void reverse(List list) {
       if (list== null || list.size() <= 1) {
           return;
       }

       Integer value = list.remove(0);

       reverse(list);

       list.add(value);
   }
}
The output is:
Array before reverse : [1, 4, 9, 16, 25] Array after reverse : [25, 16, 9, 4, 1]

Conclusion

So here we have looked at 5 different ways to reverse an array. Option 3, which uses the Collections framework, is probably the best method to use since Collections.reverse is an already existing, tried and tested, Java function. Of course the other options can be used, especially while learning, but generally standard methods, if they exist, are the best as they are usually highly optimized and tested. However, you may create such methods yourself since this is a good coding exercise and will help you succeed in your interview for Java Junior.
Comments (1)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Hoist Level 32, San Diego, United States
9 October 2021
Great Array data storage use case examples of the 'shrink wrapped' methods that come with the Java language for Array.