Reverse Java Array: Methods & Examples
You can reverse a Java array using the following methods:
- Use a loop to create a new array, traverse the original array starting from the end, and place the elements into the new array sequentially.
public static void reverseArray(int[] arr) {
int[] reversedArray = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
reversedArray[i] = arr[arr.length - 1 - i];
}
for (int i = 0; i < arr.length; i++) {
arr[i] = reversedArray[i];
}
}
- Use the Collections.reverse() method: convert the array to a List, and then reverse it using the Collections.reverse() method.
import java.util.Arrays;
import java.util.Collections;
public static void reverseArray(int[] arr) {
Integer[] integerArr = Arrays.stream(arr).boxed().toArray(Integer[]::new);
Collections.reverse(Arrays.asList(integerArr));
for (int i = 0; i < arr.length; i++) {
arr[i] = integerArr[i];
}
}
You can use either of these two methods to reverse the array. Just choose one to use.