How to Reverse an array in Java

Reversing an array in Java can be done in several ways. To reverse an array, we need to rearrange its elements so that the values at the last index come first and the values at the first index go last. Below, I am providing different methods to reverse an array.

Method1:

In this method, we create a new array with the same length as the original array and copy the elements into it in reverse order, starting from index zero. This approach reverses the array using O(n) time complexity. Below is the code example for reversing an array using this method:

import java.util.Arrays;

import org.testng.annotations.Test;

public class ReverseArray {
@Test
public void reverse() {
int[] arr1 = {1,5,9,2,7,8};

 int len = arr1.length;
 int[] reverseArr = new int[len];
 for(int i=len-1;i>=0;i--) {
     reverseArr[len-1-i] = arr1[i];
 }

 System.out.println(Arrays.toString(reverseArr));

}
}

Method 2:

In this method, we swap the values from the beginning and the end of the array step by step. We store one value in a temporary variable during each swap to avoid losing it. After each swap, we move the start index forward and the end index backward to continue swapping the next pair of elements.
This approach reverses the elements in the same array without creating a new one. This approach reverses the array using O(n/2) operations, which simplifies to O(n) time complexity. Below is the code example for reversing an array using this method:

package tests;

import java.util.Arrays;

import org.testng.annotations.Test;

public class ReverseArray {
@Test
public void reverse() {
int[] arr1 = {1,5,9,2,7,8};

 int len = arr1.length;
 int start = 0;
 int end = len-1;
 int temp = 0;
 while(start<=end) {
     temp = arr1[start];
     arr1[start] = arr1[end];
     arr1[end] = temp;
     start++;
     end--;
 }

 System.out.println(Arrays.toString(arr1));

}
}

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , Smart Fitness Guide , CodesToolbox , Testing Forum
Scroll to Top
0
Would love your thoughts, please comment.x
()
x