Reverse an array in Java

Reverse an array in Java

Example – Java program to Reverse an Array

Reversing an array in java can be done using in-built java method or non in- built java method

public class ReverseArray { 
    static void reverseArrayMethod(int originalArray[], int length) 
    { 
        int[] tempArray = new int[length]; 
        int j = length; 
        for (int i = 0; i < length; i++) { 
          tempArray[j - 1] = originalArray[i]; 
            j = j - 1; 
        } 

        System.out.print("Reversed array is: "); 
        for (int k = 0; k < length; k++) { 
            System.out.print(tempArray[k]+" "); 
        } 
    } 

    public static void main(String[] args) 
    { 
        int originalArray[] = {10, 20, 30, 40, 50}; 
        reverseArrayMethod(originalArray, originalArray.length); 
    } 
} 

Output

Reversed array is: 50 40 30 20 10

Example – Reverse an array using another way

import java.util.*;

public class ReverseArray {

  public static String[] reverseArrayMethod(String[] originalArray) {

    if (originalArray == null || originalArray.length <= 1) {
      return originalArray;
    }

    for (int i = 0; i < originalArray.length / 2; i++) {
      String value = originalArray[i];
      originalArray[i] = originalArray[originalArray.length - 1 - i];
      originalArray[originalArray.length - 1 - i] = value;
    }
    return originalArray;

  }

  public static void main(String args[]) {

    String[] originalArray = { "Java", "Proedu", "Questions" };
    System.out.println("original array: " + Arrays.toString(originalArray));

    originalArray= reverseArrayMethod(originalArray);
    System.out.println("reversed array: " + Arrays.toString(originalArray) );
  }
}

Output

original array: [Java, Proedu, Questions]
reversed array: [Questions, Proedu, Java]

Example – Using Collections.reverse(List list)

Another easy way to reverse an array in Java is to first convert the array to a list and then use a collections.reverse() method that accepts a list and reverses elements . collection. The time complexity of the reverse () method is O (n).

import java.util.*;

public class ReverseArray {

  static void reverseArrayMethod(Integer originalArray[]) {
    Collections.reverse(Arrays.asList(originalArray));
    System.out.println("Reverse Array "+Arrays.asList(originalArray));
  }

  public static void main(String[] args) {
    Integer[] originalArray = { 50, 60, 70, 80, 90 };
    System.out.println("Original Array "+Arrays.asList(originalArray));
    reverseArrayMethod(originalArray);
  }
}

Output

Original Array [50, 60, 70, 80, 90]
Reverse Array [90, 80, 70, 60, 50]