How to Reverse an int Array in Java with Example

There are multiple ways we can perform how to reverse an array in java with example. Reversing an array is an easy question. Let understand the question through the example :

Input    : {3, 8, 5, 7, 4}
Output : {4, 7, 5, 8, 3}

Input     : {10, 54, 23, 89, 97, 2}
Output  : {2, 97, 89, 23, 54, 10}

Read Also :   How to reverse a string in java with Example


Pseudo Code for Reverse Array in Java Method 1:

1. Swap the values of left indices with the right indices till the mid element.




import java.util.*;
class ReverseArray
{
    public static void main (String[] args) throws java.lang.Exception
    {
        int[] temp = {3,7,9,6,4};
        System.out.println("Array without reverse" + Arrays.toString(temp));
        reverseArray(temp);
    }
    public static void reverseArray(int[] data) {
        for (int left = 0, right = data.length - 1; left < right; left++, right--){
            // swap the values at the left and right indices
            int temp = data[left];
            data[left]  = data[right];
            data[right] = temp;
        }
        System.out.print("Reverse Array :");
        for(int val : data)
            System.out.print(" "+val);
    }
}


Please find the reverse an array in java image below for  method 1:

Reverse Array in Java with Example
Reverse Array in Java Example




Pseudo Code for Reverse Array in Java Method 2:

1. Convert the object array to the list.
2. Reverse the list using Collections.reverse() method
3. Convert the list back to the array.

public static Object[] reverseArray(Object[] arr) {
    List<Object> list = Arrays.asList(arr);
    Collections.reverse(list);
    return list.toArray();
}


Please mention in the comments in case if you know any other way to reverse array in java.



About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry