Examples
- Java Program to Count Number of Digits in Number (Integer Length)
- Java Program to Reverse a String (4 Methods)
- How to Reverse an Array in Java? Array Reverse Program
- How to Find Power of a Number in Java? 4 Programs
- How to Find Factors of a Number in Java? Factors Program
- Check Disarium Number in Java (3 Easy Programs)
- Find Keith Number in Java (Easy Programs)
- Happy Number in Java (Easy Programs With Logic)
- Find Sunny Number in Java (Easy Programs)
How to Reverse an Array in Java? Array Reverse Program
Arrays in Java are a fundamental data structure, allowing you to store and manipulate collections of elements efficiently. Sometimes, you may need to reverse the order of elements within an array.
Whether you're a beginner looking to learn the basics of array manipulation or an experienced developer seeking a quick refresher, this tutorial will provide you with a step-by-step guide on how to reverse an array in Java.
Reversing an array is a common operation in programming and can be essential for various applications. You might need to reverse an array to display its elements in reverse order, process data from the end to the beginning, or solve specific coding challenges efficiently.
In this tutorial, we'll explore different techniques and methods to reverse arrays in Java, from the traditional iterative approach to more concise and modern solutions introduced in recent versions of the language. We'll cover a range of scenarios, including reversing arrays of primitive data types and reversing arrays of objects.
Concepts to Learn:
Program for Array Reverse in Java (Iterative Approach)
Here's how to reverse an array in Java using for loop and the iterative approach:
Code
public class ReverseArray {
public static void main(String[] args) {
int[] originalArray = {1, 2, 3, 4, 5};
int length = originalArray.length;
int[] reversedArray = new int[length];
for (int i = 0; i < length; i++) {
reversedArray[i] = originalArray[length - 1 - i];
}
// Print the reversed array
System.out.print("Reversed Array: ");
for (int num : reversedArray) {
System.out.print(num + " ");
}
}
}
Output
Reversed Array: 5 4 3 2 1
Explanation
-
We start with the original array {1, 2, 3, 4, 5} and create a new array reversedArray of the same length to store the reversed elements.
-
We iterate through the original array using a for loop with an index variable i. For each element in the original array, we calculate the corresponding position in the reversed array using length - 1 - i.
-
We assign the element from the original array to the reversed array in reverse order.
-
Finally, we print the reversed array, which gives us the output {5, 4, 3, 2, 1}, effectively reversing the original array using the iterative approach.
Reverse Array in Java Using Collections.reverse()
Here's how to reverse an array in Java using the Collections.reverse() method for ArrayLists:
Code
import java.util.ArrayList;
import java.util.Collections;
public class ReverseArrayList {
public static void main(String[] args) {
ArrayList<Integer> originalList = new ArrayList<>();
originalList.add(1);
originalList.add(2);
originalList.add(3);
originalList.add(4);
originalList.add(5);
// Reverse the ArrayList
Collections.reverse(originalList);
// Print the reversed ArrayList
System.out.print("Reversed ArrayList: ");
for (int num : originalList) {
System.out.print(num + " ");
}
}
}
Output
Reversed ArrayList: 5 4 3 2 1
Explanation
-
We start by creating an ArrayList named originalList and populate it with integers {1, 2, 3, 4, 5}.
-
To reverse the ArrayList, we use the Collections.reverse() method, which is a convenient utility provided by the Java Collections Framework.
-
After calling Collections.reverse(originalList), the originalList is reversed in place.
-
Finally, we iterate through the reversed ArrayList and print its elements, which results in the output {5, 4, 3, 2, 1}, effectively reversing the ArrayList using the Collections.reverse() method.
Reverse an Array in Java Using Arrays.copyOf()
Here's how to reverse an array in Java using the Arrays.copyOf() method for a copy-based approach:
Code
import java.util.Arrays;
public class ReverseArrayCopy {
public static void main(String[] args) {
int[] originalArray = {1, 2, 3, 4, 5};
int length = originalArray.length;
int[] reversedArray = new int[length];
for (int i = 0; i < length; i++) {
reversedArray[i] = originalArray[length - 1 - i];
}
// Print the reversed array
System.out.print("Reversed Array: ");
for (int num : reversedArray) {
System.out.print(num + " ");
}
}
}
Output
Reversed Array: 5 4 3 2 1
Explanation
-
Similar to the first method, we start with the original array {1, 2, 3, 4, 5} and create a new array reversedArray of the same length to store the reversed elements.
-
We iterate through the original array using a for loop with an index variable i. For each element in the original array, we calculate the corresponding position in the reversed array using length - 1 - i.
-
We assign the element from the original array to the reversed array in reverse order.
-
The key difference in this method is that we use the Arrays.copyOf() method to create a copy of the reversed array. The copy is made from the reversedArray, which effectively contains the reversed elements.
-
Finally, we print the reversed array, which gives us the output {5, 4, 3, 2, 1}, effectively reversing the original array using a copy-based approach with Arrays.copyOf().
Array Reverse Program in Java Using Stream API
Here's how to reverse an array in Java using the Stream API (Java 8 and later):
Code
import java.util.Arrays;
public class ReverseArrayUsingStream {
public static void main(String[] args) {
int[] originalArray = {1, 2, 3, 4, 5};
int[] reversedArray = Arrays.stream(originalArray)
.boxed()
.sorted(Collections.reverseOrder())
.mapToInt(Integer::intValue)
.toArray();
// Print the reversed array
System.out.print("Reversed Array: ");
for (int num : reversedArray) {
System.out.print(num + " ");
}
}
}
Output
Reversed Array: 5 4 3 2 1
Explanation
We use the Stream API introduced in Java 8 to perform the reversal.
-
Arrays.stream(originalArray) creates a stream of integers from the original array.
-
.boxed() converts the stream of integers into a stream of Integer objects.
-
.sorted(Collections.reverseOrder()) sorts the stream in reverse order, effectively reversing the elements.
-
.mapToInt(Integer::intValue) converts the stream of Integer objects back to a stream of primitive integers.
-
.toArray() collects the stream elements into an integer array, resulting in the reversed array.
Finally, we print the reversed array, which gives us the output {5, 4, 3, 2, 1}, effectively reversing the original array using the Stream API.
Array Reverse in Java Using Deque Interface
Here's how to reverse an array in Java using the Deque interface from the Java Collections Framework:
Code
mport java.util.ArrayDeque;
import java.util.Deque;
public class ReverseArrayUsingDeque {
public static void main(String[] args) {
int[] originalArray = {1, 2, 3, 4, 5};
int length = originalArray.length;
Deque<Integer> deque = new ArrayDeque<>();
// Push elements from the original array onto the deque in reverse order
for (int i = length - 1; i >= 0; i--) {
deque.push(originalArray[i]);
}
int[] reversedArray = new int[length];
// Pop elements from the deque to get the reversed array
for (int i = 0; i < length; i++) {
reversedArray[i] = deque.pop();
}
// Print the reversed array
System.out.print("Reversed Array: ");
for (int num : reversedArray) {
System.out.print(num + " ");
}
}
}
Output
Reversed Array: 5 4 3 2 1
Explanation
-
We create a Deque<Integer> named deque, which is a double-ended queue provided by the Java Collections Framework.
-
We push elements from the original array onto the deque in reverse order using a for loop. This effectively reverses the order of elements in the deque.
-
Next, we create a new integer array reversedArray of the same length as the original array to store the reversed elements.
-
We pop elements from the deque using a second for loop to obtain the reversed order of elements.
Finally, we print the reversed array, which gives us the output {5, 4, 3, 2, 1}, effectively reversing the original array using the Deque interface and a double-ended queue.
Array Reverse in Java Using Recursion
The last method involves using recursion to reverse an array in Java. Here's how you can do it:
Code
public class ReverseArrayUsingRecursion {
public static void main(String[] args) {
int[] originalArray = {1, 2, 3, 4, 5};
int length = originalArray.length;
reverseArray(originalArray, 0, length - 1);
// Print the reversed array
System.out.print("Reversed Array: ");
for (int num : originalArray) {
System.out.print(num + " ");
}
}
// Recursive method to reverse an array
private static void reverseArray(int[] arr, int startIndex, int endIndex) {
if (startIndex < endIndex) {
// Swap the elements at startIndex and endIndex
int temp = arr[startIndex];
arr[startIndex] = arr[endIndex];
arr[endIndex] = temp;
// Recursive call on the remaining subarray
reverseArray(arr, startIndex + 1, endIndex - 1);
}
}
}
Output
Reversed Array: 5 4 3 2 1
Explanation
We start with the original array {1, 2, 3, 4, 5} and calculate its length.
-
We define a reverseArray method that takes the array, a startIndex, and an endIndex as parameters. This method will recursively reverse the subarray defined by the startIndex and endIndex.
-
Inside the reverseArray method, we check if startIndex is less than endIndex. If this condition is met, we proceed with the reversal.
-
We swap the elements at startIndex and endIndex to reverse them.
-
Then, we make a recursive call to reverseArray with the updated startIndex and endIndex, effectively reversing the remaining subarray.
-
The recursion continues until startIndex is no longer less than endIndex, at which point the array is fully reversed.
Finally, we print the reversed array.
Learn Next: