Reverse an Array in Java
To reverse an array in Java, you can swap elements from the two ends of the array, copy the elements into a second array in reverse order, or use a library method such as ArrayUtils.reverse(). The best approach depends on whether the original array may be modified and whether you are working with a Java array or an ArrayList.
Java does not provide an Arrays.reverse() method for ordinary arrays. For a plain Java array, an in-place two-pointer loop is usually the simplest approach when you do not need to preserve the original order.
Reverse a Java Array In Place Using a For Loop
An in-place reversal exchanges the first element with the last element, the second element with the second-last element, and so on. Only half of the array needs to be traversed.
For an array of length n, the element at index i is paired with the element at index n - 1 - i.
import java.util.Arrays;
public class ReverseArray {
public static void main(String[] args) {
int[] numbers = {1, 4, 9, 16, 25};
for (int left = 0, right = numbers.length - 1;
left < right;
left++, right--) {
int temp = numbers[left];
numbers[left] = numbers[right];
numbers[right] = temp;
}
System.out.println(Arrays.toString(numbers));
}
}
Output
[25, 16, 9, 4, 1]
This method changes the original array. Its time complexity is O(n), and it uses O(1) additional space because no second array is created.
Reverse a Java Array Without Modifying the Original Array
If the original array must remain unchanged, create another array of the same length and place each source element at its corresponding position from the other end.
import java.util.Arrays;
public class ReverseArrayCopy {
public static void main(String[] args) {
int[] original = {10, 20, 30, 40};
int[] reversed = new int[original.length];
for (int i = 0; i < original.length; i++) {
reversed[original.length - 1 - i] = original[i];
}
System.out.println("Original: " + Arrays.toString(original));
System.out.println("Reversed: " + Arrays.toString(reversed));
}
}
Output
Original: [10, 20, 30, 40]
Reversed: [40, 30, 20, 10]
This approach also takes O(n) time, but it requires O(n) additional space for the new array.
Example 1 – Inplace Array Reverse – ArrayUtils.reverse()
If Apache Commons Lang is already used by an application, its ArrayUtils utility can reverse an array in place. The following existing example uses the org.apache.commons.lang.ArrayUtils package used by the older Commons Lang API.
ArrayUtils.reverse() reverses the array in place. In other words, the method modifies the original array rather than returning a separate reversed array.
Java Program
import org.apache.commons.lang.ArrayUtils;
/**
* Java Program - Reverse Array
*/
public class ArrayReverse {
public static void main(String[] args) {
//two arrays
int[] arr1 = {1, 4, 9};
//inplace reverse
ArrayUtils.reverse(arr1);
//print the array
for(int num: arr1)
System.out.println(num);
}
}
Console Output
9
4
1
If you want to keep the original array unchanged, first clone it and then reverse the clone.
In the following example, arr1 is cloned into result. The reverse operation is then applied only to the result array.
Java Program
import org.apache.commons.lang.ArrayUtils;
/**
* Java Example Program, to Reverse Array
*/
public class ArrayReverse {
public static void main(String[] args) {
//two arrays
int[] arr1 = {1, 4, 9};
//array reverse
int[] result = arr1.clone();
ArrayUtils.reverse(result);
//print the array
for(int num: result) System.out.println(num);
}
}
Output
9
4
1
The cloned integer array is reversed while the original array remains available in its initial order.
Example 2 – Reverse Java Array Using a For Loop and a Second Array
In this example, we shall use Java For Loop to reverse the array. Following is the sequence of steps, that we shall execute in the below program.
- Create an empty
resultarray with the same size as that of original array. - Use for loop, to traverse through the elements of the original array
arr1from start to end. While traversing, store the elements in theresultarray from end to start. - After the loop is over,
resultarray contains the elements of original arrayarr1arranged in a reverse order.
Java Program
/**
* Java Program - Reverse Array
*/
public class ArrayReverse {
public static void main(String[] args) {
int[] arr = {1, 4, 9};
//array reverse
int[] result = new int[arr.length];
for(int i = 0; i < arr.length; i++) {
result[arr.length-1-i] = arr[i];
}
//print the array
for(int num: result)
System.out.println(num);
}
}
Output
9
4
1
The expression arr.length - 1 - i calculates the destination index from the opposite end of the result array. For example, when i is 0, the first source element is stored at the last result index.
Example 3 – Reverse a Java Array Using a While Loop
We can also use Java While Loop statement to reverse an array.
In the following example, an integer array is traversed with a while loop and its values are stored in another array in reverse order.
Java Program
/**
* Java Program - Reverse Array
*/
public class ReverseArray {
public static void main(String[] args) {
//number
int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9};
//variable to hold reversed array
int[] reverse = new int[nums.length];
//reverse array
int i = 0;
while( i < nums.length ) {
reverse[nums.length-1-i] = nums[i];
i++;
}
//print reversed array
for(int n: reverse)
System.out.print(n+" ");
}
}
Output
9 8 7 6 5 4 3 2 1
Reverse an Array in Java Using User Input
When the array values are entered at runtime, read the values first and then apply the same left-and-right swap technique. The reversal algorithm does not depend on how the array was created.
import java.util.Arrays;
import java.util.Scanner;
public class ReverseInputArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter array size: ");
int size = scanner.nextInt();
int[] numbers = new int[size];
System.out.println("Enter " + size + " integers:");
for (int i = 0; i < size; i++) {
numbers[i] = scanner.nextInt();
}
for (int left = 0, right = numbers.length - 1;
left < right;
left++, right--) {
int temp = numbers[left];
numbers[left] = numbers[right];
numbers[right] = temp;
}
System.out.println("Reversed array: " + Arrays.toString(numbers));
scanner.close();
}
}
Example run
Enter array size: 5
Enter 5 integers:
10 20 30 40 50
Reversed array: [50, 40, 30, 20, 10]
Why Java Has No Arrays.reverse() Method
The standard java.util.Arrays utility class contains many array operations, but it does not provide a general Arrays.reverse() method. Therefore, code such as Arrays.reverse(numbers) is not a valid standard Java array operation.
For primitive arrays such as int[], double[], and char[], use a loop or a suitable third-party utility when reversal is required.
Reverse an Object Array with Collections.reverse()
For an array of objects such as String[], the array can be viewed as a list using Arrays.asList() and then reversed with Collections.reverse(). The list returned by Arrays.asList() is backed by the original object array, so reversing the list also changes the array.
import java.util.Arrays;
import java.util.Collections;
public class ReverseStringArray {
public static void main(String[] args) {
String[] names = {"Asha", "Bina", "Charan"};
Collections.reverse(Arrays.asList(names));
System.out.println(Arrays.toString(names));
}
}
Output
[Charan, Bina, Asha]
This technique should not be used in the same way for a primitive array such as int[]. Passing an int[] to Arrays.asList() does not create a list containing each integer as a separate element; the primitive array itself becomes a single list element.
Reverse an ArrayList in Java with Collections.reverse()
An ArrayList is a List, so it can be reversed directly using Collections.reverse(). This is different from reversing a primitive Java array.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class ReverseArrayList {
public static void main(String[] args) {
ArrayList<Integer> numbers =
new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Collections.reverse(numbers);
System.out.println(numbers);
}
}
Output
[5, 4, 3, 2, 1]
How Java Array Reversal Handles Empty and Single-Element Arrays
The two-pointer loop also works for arrays containing zero or one element. For an empty array, the right index starts at -1, so the loop condition is false immediately. For a one-element array, the left and right indexes are both 0, so no swap is necessary.
A null array is different. Trying to access array.length when the reference is null causes a NullPointerException. A reusable reversal method can explicitly handle or reject null according to the requirements of the application.
Reusable Method to Reverse an int Array in Java
If array reversal is needed in several places, move the swap logic into a method. The following method modifies the supplied int[] in place.
public static void reverse(int[] array) {
if (array == null) {
return;
}
int left = 0;
int right = array.length - 1;
while (left < right) {
int temp = array[left];
array[left] = array[right];
array[right] = temp;
left++;
right--;
}
}
Because arrays are objects in Java, the method receives a reference to the same array object. Swapping its elements therefore changes the array seen by the caller.
Choosing the Right Java Array Reverse Technique
- Use an in-place two-pointer loop when the original array may be modified and you want constant additional space.
- Create a second reversed array when the original order must remain unchanged.
- Use
Collections.reverse()for anArrayListor for an object array viewed throughArrays.asList(). - Use
ArrayUtils.reverse()when the appropriate Apache Commons Lang dependency is already part of the project.
For a plain primitive array such as int[], the in-place swap loop is usually the most direct solution because it requires no additional library and no second array.
Java Array Reverse Summary
In this Java Tutorial, we learned how to reverse an array using an in-place swap loop, a separate result array, a while loop, user input, Apache ArrayUtils.reverse(), and Collections.reverse() for suitable list-backed object arrays. We also saw why Arrays.reverse() is not available for standard Java arrays and why primitive arrays such as int[] need different handling from an ArrayList.
TutorialKart.com