Reverse java array
Reverse an array means rearranging the elements of the array in such a way that the last element is placed at first position, second last element to second position and so on.
There are many ways to reverse a java array. 6 of them are explained in this article.

Refer this post to learn how to define an array in java.

Method 1 : Using start and end pointers to the array
This method sets up two pointers, one pointing towards the start of the array (index 0) and the other pointing to its end (length of array – 1, since array index starts from 0).

Iteration of array is then started and in each iteration, the value at the index pointed by the start pointer is swapped by the value at the index pointed by end pointer using a temporary variable.
This is followed by incrementing start pointer and decreasing end pointer by 1. The iteration is performed till the start and end pointers do not cross.

public static void reverse() {
  int[] array = { 3, 56, 2, 6, 8, 12, 5, 8 };
  System.out.println("Before");
  for (int num : array) {
     System.out.print(num);
     System.out.print(" ");
  }
  // initialize start and end counters
  int start = 0;
  int end = array.length - 1;
  while (start < end) {
    // swap the values at the left and right indices
    int temp = array[start];
    array[start] = array[end];
    array[end] = temp;
    // increase start counter
    start++;
    // decrease end counter
    end--;
  }
  System.out.println("After");
  for (int num : array) {
    System.out.print(num);
    System.out.print(" ");
  }
}

Output :

Before
3 56 2 6 8 12 5 8
After
7 8 5 12 8 6 2 56 3


Method 2
: Mid array iteration
This method is somewhat similar to above method. The difference is that instead of managing two pointers to the array, we iterate over the array till its mid index.

In each iteration, the value towards the start of the array is swapped with the value towards the end of the array using a temporary variable.
When iterations complete, all elements towards the right of the middle of array are swapped with the elements towards the left of array middle.

public static void reverse() {
   int[] array = { 3, 56, 2, 6, 8, 12, 5, 8 };
   System.out.println("Before");
   for (int num : array) {
      System.out.print(num);
      System.out.print(" ");
   }
   for (int i = 0; i < array.length / 2; i++) {
     int temp = array[i];
     array[i] = array;
     array = temp;
   }
   System.out.println("After");
   for (int num : array) {
     System.out.print(num);
     System.out.print(" ");
   }
}

Print the array and you will get the below output

Before
3 56 2 6 8 12 5 8
After
7 8 5 12 8 6 2 56 3

Method 3 : Using java.util.Collections
This method involves converting the array to a java.util.ArrayList which is then passed to reverse() method of java.util.Collections class and it does the rest.

public static void reverse() {
   Integer[] array = { 3, 56, 2, 6, 8, 12, 5, 8 };
   System.out.println("Before");
   for (int num : array) {
      System.out.print(num);
      System.out.print(" ");
   }  
   // convert array to list
   List list = Arrays.asList(array);
   // reverse the list
   Collections.reverse(list);
   // convert to array again
   Object[] objectArray = list.toArray();
   for (int i = 0; i < objectArray.length; i++) {
      // cast to int needed  
      System.out.print((int) objectArray[i]);
      System.out.print(" ");
   }
}

Output :

Before
3 56 2 6 8 12 5 8
After
7 8 5 12 8 6 2 56 3

If you look at this program closely, then actually it is reversing a list created after the converting the array into a list.
Method 4 : Using Apache Commons Library
This method uses reverse()method of org.apache.commons.lang.ArrayUtils class of Apache commons lang library.
This method takes the array to reverse as an argument and reverses its contents.
If you can use an external library in your project, then this is the shortest method to reverse an array.

public static void reverse() {
   int[] array = { 3, 56, 2, 6, 8, 12, 5, 8 };
   System.out.println("Before");
   for (int num : array) {
      System.out.print(num);
      System.out.print(" ");
   }
   ArrayUtils.reverse(array);
   System.out.println("After");
   for (int num : array) {
      System.out.print(num);
      System.out.print(" ");
   }
}

Output :

Before
3 56 2 6 8 12 5 8
After
7 8 5 12 8 6 2 56 3

Method 5 : Using Recursion
This method is similar to Method 1 in that it maintains pointers to the start and end of the array and swaps the element at the two positions.
The only difference is that instead of using a for loop to increase, decrease the counters and swapping elements, it uses recursion approach.

The method which performs the swapping compares the start and end pointers.
If start index is less than the end index, it calls itself increasing start pointer by 1 and decreasing end pointer by 1 in each recursive call.
This keeps on going till the start pointer passes the end pointer exchanging the elements in every recursive call.

public static void reverse() {
   int[] array = { 3, 56, 2, 6, 8, 12, 5, 8 };
   System.out.println("Before");
   for (int num : array) {
 	System.out.print(num);
	System.out.print(" ");
   }
   reverseArray(array, 0, array.length - 1);
   System.out.println("After");
   for (int num : array) {
	System.out.print(num);
	System.out.print(" ");
   }
}

// Method which will recursively reverse the array
static void reverseArray(int[] array, int start, int end) {
   if (start < end) {
	// swap elements at given index
	int temp = array[start];
	array[start] = array[end];
	array[end] = temp;
	// recursive call
	// increase start index and decrease end index
	reverseArray(array, ++start, --end);
   }
}

Output :

Before
3 56 2 6 8 12 5 8
After
7 8 5 12 8 6 2 56 3

Method 6: Reverse array in java 8
Java 8 streams can be used to reverse an array. Example program follows.

public static void reverseArray() {
   String[] arr = { "A", "B", "C", "D", "E" };
   System.out.println("Before");
   for (String element : arr) {
	System.out.print(element);
	System.out.print(" ");
   }
   String[] reversed = (String[]) IntStream.range(1, arr.length + 1).
                        mapToObj(index -> arr[arr.length - index]).toArray();
   System.out.println("After");
   for (String element : reversed) {
	System.out.print(element);
	System.out.print(" ");
   }
}

range method of java.util.stream.IntStream class generates a stream of integers between the two arguments supplied to it.
Thus, in this example, it will generate a stream of integers from 1 till the (length of array + 1).

mapToObj() method then applies an operation on every element. The operation is supplied as an argument to mapToObj().
In every call to mapToObj(), the value of index variable is an integer starting from 1 till the (length of array + 1) and it returns array elements from indexes (length – 1) till 0, that is, from the end of array to the beginning.

All the elements returned from mapToObj() are collected to an array with toArray() method.
Output of above example is

Before
A B C D E
After
E D C B A

If you are aware of other methods to reverse an array, do let our readers know by adding a comment in the space below !!!
Hit the clap if you learnt a new method to reverse an array.

Leave a Reply