Reverse an Array in Java

In this article, we will discuss how to reverse an array in Java.

So, if we provide an array of [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] to the program, the output will be an array with elements in reverse order, i.e. [10, 9, 8, 7, 6, 5, 4, 3, 2, 1].

Here is the program :

package com.topjavatutorial;

public class ArrayReverse {

  public static void main(String[] args) {
    int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    
    System.out.println("Original Array : ");
    
    for (int a : array) {
      System.out.print(a + " ");
    }

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

    System.out.println("\nReversed Array : ");
    for (int value : array) {
      System.out.print(value + " ");
    }
  }
}

Output :

Original Array :
1 2 3 4 5 6 7 8 9 10
Reversed Array :
10 9 8 7 6 5 4 3 2 1

 

We can also convert the array to an ArrayList and use the Collections.reverse() method.

Here is the code :

package com.topjavatutorial;

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

public class ArrayReverse {

  public static void main(String[] args) {
    List<Integer> arrayList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    
    System.out.println("Original Array : " + arrayList);
    
    Collections.reverse(arrayList);
  
    System.out.println("\nReversed Array : " + arrayList); 
  }
}

Output :

Original Array : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Reversed Array : [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

 

© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags