For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
Reversing an array in Java is a common and simple task for beginners and experienced developers as well. By “reversing” an array, it means changing the order of its elements so that the last element becomes the first one, and the first element changes to the last. Whether you’re preparing for coding interviews or improving your Java skills, learning how to reverse an array is a great way to practice.
Do you know why it is important? The main reason is reversing an array helps you get comfortable with concepts like indexing and array iteration. And, also in most of the developer hiring interviews, they ask you to reverse an array or a string), as they evaluate your understanding of data structure.
Select the approach according to your particular requirements, including if you aim to alter the original array or generate a new one.
Enhance your Java programming skills with our Software Development courses and take your learning to the next level!
In this article, you will learn more about Reverse an Array in Java, the difference between iterative and recursive array reversal, important questions for interview preparation, and also practice exercise suggestions.
Array Reversal is the process of taking an array (a list of elements) and flipping the order of its contents. Let's take an example, if you have an array(1,2,3,4,5), reversing it results: in (5,4, 3,2,1). This might seem simple, but this operation plays an important role in many tasks, such as checking for palindromes or performing certain types of sorting and searching algorithms.
Reversing an array in Java (or any programming language) usually involves swapping elements from opposite ends until you reach the middle. And, this can be done manually with a loop or by using built-in utilities. It is a basic, yet important, concept to learn because it helps you understand how arrays work, and how to manipulate data, and can lead to more advanced problem-solving skills.
Applications where this approach is utilized encompass producing reports in reverse chronological sequence or presenting data in descending sequence according to specific criteria. In Java, you can reverse an array using different methods, each offering distinct advantages and disadvantages concerning simplicity, efficiency, and memory consumption. Here are the various methods for reversing an array in Java:
Also Read: How to do Reverse String in Java?
When you use a temporary array, it is one of the easiest ways to reverse an array. The first step is to create a new array with the same length as your original one. Then, the next step is to copy the elements from the original array into the new array in reverse order, which means the first element of the original goes to the last position of the new array, the second element goes to the second-last position, and so on.
Once the copy is completed, you have an entire reversed version of the original array. This method can be simpler to understand, but it requires extra space since you’re creating a second array.
Approach:
Example Code:
public class ArrayReversalUsingTemporaryArray {
// Method to reverse the array using a temporary array
public static void reverseArray(int[] arr) {
// Create a temporary array with the same size as the original array
int[] temp = new int[arr.length];
// Loop to copy the elements in reverse order to the temporary array
for (int i = 0; i < arr.length; i++) {
temp[i] = arr[arr.length - 1 - i]; // Copy elements in reverse order
}
// Copy the elements back from the temporary array to the original array
for (int i = 0; i < arr.length; i++) {
arr[i] = temp[i];
}
}
// Helper method to print the array
public static void printArray(int[] arr) {
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
public static void main(String[] args) {
// Sample array to reverse
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
System.out.println("Original Array:");
printArray(arr);
// Reverse the array using the temporary array approach
reverseArray(arr);
System.out.println("Array after reversal:");
printArray(arr);
}
}
Explanation:
reverseArray(int[] array):
Temporary Array: We generate a temporary array temp that matches the length of the original array arr.
Initial Loop (Reversal): The loop traverses the original array and places each element into the temporary array in reverse sequence. This is achieved by accessing elements of arr starting from the last element (arr.length - 1) and proceeding to the first element (0).
Second Loop (Copying Back): Once the array has been reversed into the temporary array, the second loop transfers the values from the temporary array to the original array.
printArray(int[] arr): This function displays the array elements prior to and following the reversal.
Output:
For the given array {1, 2, 3, 4, 5, 6, 7, 8, 9}, the output will be:
Original Array:
1 2 3 4 5 6 7 8 9
Array after reversal:
9 8 7 6 5 4 3 2 1
In this two-point approach, you do not need to create a new array. On the contrary, you use two variables(pointers) to swap elements in the existing array. Where one pointer starts at the beginning, and the other pointer starts at the end.
Then, you exchange the values at these two positions and move both pointers closer to the middle. Repeat this process until they meet in the center of the array.
Here’s how you can utilize the two-pointer technique to reverse an array directly in Java:
Method:
Example Code:
public class ArrayReversalTwoPointer {
// Method to reverse the array using two-pointer approach
public static void reverseArray(int[] arr) {
int start = 0;
int end = arr.length - 1;
// Swap elements while the start pointer is less than the end pointer
while (start < end) {
// Swap the elements at the start and end pointers
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
// Move the pointers toward each other
start++;
end--;
}
}
// Helper method to print the array
public static void printArray(int[] arr) {
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
public static void main(String[] args) {
// Sample array to reverse
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
System.out.println("Original Array:");
printArray(arr);
// Reverse the array using the two-pointer approach
reverseArray(arr);
System.out.println("Array after reversal:");
printArray(arr);
}
}
Explanation:
reverseArray(int[] array):
printArray(int[] array):
Output:
For the given array {1, 2, 3, 4, 5, 6, 7, 8, 9}, the output will be:
Original Array:
1 2 3 4 5 6 7 8 9
Array after reversal:
9 8 7 6 5 4 3 2 1
This method is highly effective regarding both time and space. It utilizes only a fixed quantity of additional space (for the swap) and handles each element in one pass through the array.
It’s perfect for inverting large arrays when memory consumption is a priority.
Reversing an array with recursion means splitting the task down into a number of pieces, repeated steps until you attain the simplest case. In this method, a function keeps calling itself while moving two pointers, one at the start and one at the end, closer to the center of the array. Each call performs a swap, and then moves the pointers by one position inward.
Once the start pointer meets or crosses the end pointer, the function stops. This approach does not use loops, so it’s a neat way to see how recursion works. You need to remember that recursive solutions use extra memory on the call stack, which may make them less efficient than in-place methods for very large arrays.
Example Code:
public class ArrayReversalUsingRecursion {
// Recursive method to reverse the array
public static void reverseArray(int[] arr, int start, int end) {
// Base case: If start index is greater than or equal to end index, stop recursion
if (start >= end) {
return;
}
// Swap the elements at start and end
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
// Recursively call for the next portion of the array
reverseArray(arr, start + 1, end - 1);
}
// Helper method to print the array
public static void printArray(int[] arr) {
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
System.out.println("Original Array:");
printArray(arr);
// Call the recursive method to reverse the array
reverseArray(arr, 0, arr.length - 1);
System.out.println("Array after reversal:");
printArray(arr);
}
}
Explanation:
reverseArray Method:
printArray Method:
Output:
For the given array {1, 2, 3, 4, 5, 6, 7, 8, 9}, the output will be:
Original Array:
1 2 3 4 5 6 7 8 9
Array after reversal:
9 8 7 6 5 4 3 2 1
Utilize recursion when the issue presents a natural recursive pattern (such as tree traversal, divide and conquer methods, backtracking challenges) and when the clarity and elegance of the code gained from recursion surpass any possible drawbacks.
Using the Collections Framework is one of the quick ways to reverse an array of objects in Java. First, convert your array to a List using Arrays.asList(). Then, call Collections.reverse() to change the order of the elements in the List. This approach is very straightforward and simple, but it only works directly on object arrays (like Integer[]) rather than primitive arrays (like int[]).
After reversing, you can print the reversed List or convert it back to an array if you need one. However, this approach remains simple and easy, but keep in mind that for large amounts of data or critical performance scenarios, manually reversing the array might be faster and more flexible.
Here’s a method to reverse an array utilizing the Collections framework:
Process of Implementation in Steps:
Transform the array into a List by utilizing Arrays.asList().
Apply Collections.reverse() to flip the List.
Example Code:
import java.util.*;
public class ArrayReversalUsingCollections {
public static void reverseArray(int[] arr) {
// Convert the array to a List
List<Integer> list = new ArrayList<>();
for (int num : arr) {
list.add(num);
}
// Reverse the List
Collections.reverse(list);
// Convert the List back to an array (optional)
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
}
public static void printArray(int[] arr) {
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
System.out.println("Original Array:");
printArray(arr);
// Reverse the array using the Collections framework
reverseArray(arr);
System.out.println("Array after reversal:");
printArray(arr);
}
}
Explanation:
Output:
Original Array:
1 2 3 4 5 6 7 8 9
Array after reversal:
9 8 7 6 5 4 3 2 1
Use cases:
This method is beneficial when you wish to leverage the capabilities of the Collections framework, which provides built-in functions such as reverse().
This approach requires extra memory allocation as it transforms the array into a List and subsequently back into an array. To reduce memory consumption, it's preferable to utilize the in-place method (like using a while loop or recursion).
Also Read: What Is an Array? Understanding the Array Meaning, Types, and Practical Applications
When reversing an array, two common approaches are iterative and recursive methods. The iterative approach uses loops to swap elements, while the recursive method breaks the problem into smaller subproblems, calling itself until a base condition is met. The table below highlights the key differences between these two techniques.
Aspect | Iterative Reversal | Recursive Reversal |
Implementation Complexity | Usually straightforward, using loops and index swaps. | Can be less intuitive for beginners, but follows a clear divide-and-conquer pattern. |
Readability | Easy to understand at a glance, as all logic is in one block. | May be clearer if you’re comfortable with recursion; otherwise, it's harder to follow. |
Memory Usage | Uses constant extra space (no additional call stack). | Uses stack space for each recursive call, which can grow with array size. |
Performance | Generally fast, minimal overhead. | Similar time complexity, but extra function calls add a bit more overhead. |
Use Cases | Good default choice for most array reversals. | Suitable when recursion is explicitly desired or for educational purposes. |
Debugging | Simple iterative logic is usually easier to trace step by step. | Debugging can be more challenging due to multiple function calls in the call stack. |
Maintainability | A straightforward loop structure makes future modifications simpler. | Changes might require deeper knowledge of recursive flow, potentially complicating maintenance. |
Risk of Stack Overflow | No risk here, as no deep call stack is generated. | Large arrays can cause deep recursion and potential stack overflow issues. |
Syntax Simplicity | One block of code that’s short and familiar to most programmers. | Typically requires an additional function or parameters for boundaries, making the syntax more involved. |
int[] arr = {1, 2, 3, 4, 5};
int left = 0, right = arr.length - 1;
while (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
// arr is now reversed
public static void reverse(int[] arr, int start, int end) {
if (start >= end) return;
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
reverse(arr, start + 1, end - 1);
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
reverse(arr, 0, arr.length - 1);
// arr is now reversed
}
When working with array reversal, it's easy to make common mistakes that can lead to inefficient or incorrect results. Understanding the best practices can help ensure that your array reversal is both optimal and error-free.
Common Mistakes
int[] arr = {1, 2, 3, 4, 5};
for (int i = 0; i < arr.length / 2; i++) {
// Mistake: using arr.length - i instead of arr.length - i - 1
int temp = arr[i];
arr[i] = arr[arr.length - i]; // Potentially out of bounds
arr[arr.length - i] = temp;
}
int[] arr = {1, 2, 3, 4, 5};
// Mistake: Looping over the entire array instead of only up to the midpoint
for (int i = 0; i < arr.length; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = temp;
}
// This re-swaps elements after crossing the midpoint, often nullifying the reversal.
int[] arr = {1, 2, 3, 4, 5};
// Mistake: Using <= instead of < might cause an out-of-bounds exception
for (int i = 0; i <= arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - 1 - i]; // Could fail when i == arr.length / 2 (for certain lengths)
arr[arr.length - 1 - i] = temp;
}
int[] arr = {1, 2, 3, 4, 5};
// Mistake: No temp variable; overwrites arr[i] immediately
for (int i = 0; i < arr.length / 2; i++) {
arr[i] = arr[arr.length - 1 - i];
// arr[arr.length - 1 - i] is now overwritten; original arr[i] is lost
}
int[] arr = {}; // Empty array
// Mistake: Assuming the array always has multiple elements
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i]; // Can fail if arr.length == 0 (though in practice, the loop won't run, but no checks are done)
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = temp;
}
int[] arr = {1, 2, 3, 4, 5};
int[] temp = new int[arr.length];
// Mistake: Copying data incorrectly, causing the final order to remain unchanged or partially reversed
for (int i = 0; i < arr.length; i++) {
temp[i] = arr[i]; // This just replicates arr; forgetting to reverse indices
}
arr = temp; // After this, arr is still in the original order
Best Practices
In-place reversal, where you swap elements at the front and back of an array, is generally the simplest and most efficient method. This technique avoids additional memory usage because you don’t need a separate data structure. By carefully moving inward from both ends, you ensure each pair of elements is swapped only once, which keeps the process clear and prevents confusion.
It’s also important to write clean, readable code when reversing an array. Double-check that your loop conditions or recursive steps correctly handle all elements, including special cases like arrays of length zero or one. Keeping your logic straightforward makes it easier to identify any mistakes and maintain the code in the long run.
Some of the best practices in Array Reversal with examples:
int[] arr = {1, 2, 3, 4, 5};
int start = 0;
int end = arr.length - 1;
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
// Now arr is reversed in place.
int[] arr = {1, 2, 3, 4, 5};
// Only loop until the midpoint
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = temp;
}
// Correctly handles swaps without overwriting extra elements.
int[] arr = {}; // Could also be length 1, etc.
// If array has 0 or 1 elements, no reversal needed
if (arr.length > 1) {
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = temp;
}
}
// Safely checks for edge cases before swapping.
int[] arr = {1, 2, 3, 4, 5};
// Simple iterative approach avoids extra call stack usage
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = temp;
}
// Works for object arrays (not primitives)
Integer[] arr = {1, 2, 3, 4, 5};
java.util.List<Integer> list = java.util.Arrays.asList(arr);
java.util.Collections.reverse(list);
// 'arr' is now reversed in place because 'list' references the same array.
System.out.println(java.util.Arrays.toString(arr)); // [5, 4, 3, 2, 1]
nt[] arr = {1, 2, 3, 4, 5};
// The in-place swap loop is already O(n)
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = temp;
}
// This minimal approach keeps it fast and simple
Q: How do you reverse an array in place without using extra memory?
A: You can use a two-pointer approach. One pointer starts at the beginning, and the other starts at the end. Swap the elements at these pointers, then move both pointers inward until they meet. This method doesn’t create a new array, so it uses minimal extra memory.
Q: What’s the difference between reversing an array with iteration and recursion?
A: Iterative reversal typically uses a loop with two pointers to swap elements until you reach the middle. It’s efficient and easy to understand. Recursive reversal relies on calling the same function repeatedly, swapping elements from the outside moving inwards. While recursion can look neat, it uses extra memory on the call stack and can be slower if the array is very large.
Q: How do you reverse only a portion of the array?
A: You can apply the same two-pointer or recursive logic, but instead of starting at the very beginning, start at the index where you want to begin reversing and stop at the index where you want to end. Swap elements within just that section, leaving the rest of the array untouched.
Q: Can you use built-in methods to reverse an array in Java?
A: Yes, you can convert the array to a List using Arrays.asList() and then call Collections.reverse() on that List. However, this works only for object arrays (like Integer[]), not for primitive arrays (like int[]).
Q: What are key edge cases to consider when reversing an array?
A: Always check if the array is empty or has only one element. Reversing such arrays should be a quick operation that confirms nothing needs to be swapped. Also, watch out for null arrays if you’re dealing with references in more complex code.
Q: How do you handle reversing an array of unknown size?
A: You can dynamically read the elements into a List first, then convert it to an array, or use a data structure that can grow as needed. Afterward, you can apply the standard two-pointer or recursion method for reversal.
Q: How do you reverse only the even-indexed elements in an array?
A: You can iterate through the array or use two pointers, but skip odd indices. Only swap elements at even positions, for example, at indices 0, 2, 4, ... until your pointers meet or cross.
Q: What is the time complexity of reversing an array?
A: The time complexity is generally O(n)O(n)O(n), because you typically need to touch each element at least once to complete the reversal.
Q: Can reversing an array be done without using extra variables?
A: While you can’t avoid having at least one temporary variable for swapping in most languages, you don’t need additional data structures. The most space-efficient way is the in-place two-pointer approach, requiring only a small, constant amount of extra space for swapping.
Q: How can you modify a reversal function to also handle null or empty arrays?
A: You can add a simple check at the beginning of your reversal method. If the array is null or its length is less than 2, immediately return without doing anything. This ensures you avoid errors and wasted processing.
Also Read: Swapping of Two Numbers in Java
Below are some practice exercises on Reversing an Array in Java. Each exercise includes a question, an implementation outline, a code snippet, a brief explanation, and a sample output.
Write a program to reverse the elements of an array in Java.
Implementation Process:
Code:
public class ReverseArrayExample {
// Method to reverse the elements of the array in place
public static void reverseArray(int[] array) {
int start = 0;
int end = array.length - 1;
while (start < end) {
// Swap elements at positions 'start' and 'end'
int temp = array[start];
array[start] = array[end];
array[end] = temp;
// Move pointers towards the center
start++;
end--;
}
}
public static void main(String[] args) {
// Initialize the array
int[] numbers = {10, 20, 30, 40, 50};
// Print the original array
System.out.print("Original Array: ");
for (int num : numbers) {
System.out.print(num + " ");
}
// Reverse the array
reverseArray(numbers);
// Print the reversed array
System.out.print("\nReversed Array: ");
for (int num : numbers) {
System.out.print(num + " ");
}
}
}
Explanation
ReverseArray Method
Output:
Before reversing, the original order of the array is printed.
After calling reverseArray(numbers), the reversed array is displayed to confirm the result.
By following these steps, you’ll gain practice in manipulating array indices and performing basic in-place transformations.
Original Array: 10 20 30 40 50
Reversed Array: 50 40 30 20 10
Goal
Instead of reversing the array in place, use a separate array to store the reversed elements.
Implementation Steps
public class ReverseArrayWithNewArray {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int[] reversedArray = new int[numbers.length];
// Reverse by copying to a new array
for (int i = 0; i < numbers.length; i++) {
reversedArray[i] = numbers[numbers.length - 1 - i];
}
// Print original array
System.out.print("Original Array: ");
for (int num : numbers) {
System.out.print(num + " ");
}
// Print reversed array
System.out.print("\nReversed Array: ");
for (int revNum : reversedArray) {
System.out.print(revNum + " ");
}
}
}
Explanation
Concretely:
Output
Original Array: 10 20 30 40 50
Reversed Array: 50 40 30 20 10
The output simply shows that each element’s position is inverted relative to its original place in the array.
Goal
Practice recursion by creating a function that reverses an array using a method that calls itself.
Implementation Steps
Code
public class ReverseArrayRecursive {
// Recursive method to reverse an array
public static void reverseRecursive(int[] arr, int start, int end) {
if (start >= end) {
return; // Base case: nothing to swap if start >= end
}
// Swap elements at 'start' and 'end'
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
// Recursive call
reverseRecursive(arr, start + 1, end - 1);
}
public static void main(String[] args) {
int[] numbers = {5, 10, 15, 20, 25, 30};
// Print the original array
System.out.print("Original Array: ");
for (int num : numbers) {
System.out.print(num + " ");
}
// Call the recursive method
reverseRecursive(numbers, 0, numbers.length - 1);
// Print the reversed array
System.out.print("\nReversed Array: ");
for (int num : numbers) {
System.out.print(num + " ");
}
}
}
Explanation
Output
Original Array: 5 10 15 20 25 30
Reversed Array: 30 25 20 15 10 5
Goal
Reverse only a specific section of an array while keeping the rest unchanged.
Implementation Steps
Sample Code
public class ReversePortionOfArray {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50, 60, 70};
int start = 2, end = 5; // Reverse from index 2 to 5
// Reverse the portion using two pointers
while (start < end) {
int temp = numbers[start];
numbers[start] = numbers[end];
numbers[end] = temp;
start++;
end--;
}
// Print the modified array
System.out.print("Modified Array: ");
for (int num : numbers) {
System.out.print(num + " ");
}
}
}
Explanation of the Code
Explanation of the Output
Original Array: 10 20 30 40 50 60 70
Reversed Array: 10 20 60 50 40 30 70
Also Read: Top 12 Pattern Programs in Java You Should Checkout Today
Reversing an array in Java is one of the simple processes. One common way is to use two pointers: one at the start and one at the end of the array. Then, change the elements at these pointers and move the pointers toward each other until they meet in the middle. This effectively reverses the order of the array elements. You can implement it using a simple for loop that runs up to the midpoint of the array, Changing elements at i and length - i - 1.
Another approach is to convert the array to a List, use the Collections.reverse() method, and then convert it back to an array if needed. However, this approach is more suited to arrays of objects rather than primitive arrays. Either way, the goal is to ensure that the element currently at the front of the array is placed at the back, and you work inwards until the entire array is reversed.
In Java, reversing an array is a valuable technique, useful in a variety of scenarios where you need to reverse data order for processing or storage. The two-pointer method is highly efficient, especially when you aim to modify the array in place without using extra space.
You can explore the following courses at upGrad to strengthen your knowledge on the subject:
Book a free counseling session with upGrad experts and visit your nearest upGrad center to learn more.
Similar Reads:
An in-place approach using two pointers is often considered the best because it swaps elements from both ends of the array without extra memory, runs in O(n) time, and is straightforward to implement.
Yes, you can reverse an array in-place by swapping elements from opposite ends. This approach only uses a few variables for swapping and does not require allocating additional memory for another array.
Recursion has the same O(n) time complexity but adds overhead from multiple function calls, which consume stack space. Therefore, while recursion works fine, it is generally less efficient than an iterative approach.
Use two pointers to swap elements within the desired index range, starting from the ends and moving toward the center. This technique isolates a subrange while leaving the rest of the array unchanged.
Java’s standard libraries do not include a direct method for reversing primitive arrays. However, you can convert the array to a List, by using Collections.reverse(), then convert it back, which works for arrays of object references.
Regardless of the approach, reversing an array generally runs in O(n) time, because each element is visited once. Both iterative and recursive methods have the same asymptotic complexity, although recursion incurs additional overhead.
One approach is Collections.reverse(Arrays.asList(arr)) if arr is an array of objects. For primitive arrays, a one-line reversal is impractical because an explicit loop or method call is needed to swap elements in-place.
You can convert the array to a stream, collect it into a list, and then use Collections.reverse(). Alternatively, map the array to an IntStream (for primitives) or Stream (for objects), then reverse the collection after accumulation.
Languages like C, C++, Python, and JavaScript frequently reverse arrays in everyday tasks, such as data manipulation or implementing algorithms. Reversal is universal and used in sorting, searching, or simply rearranging elements in various languages.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.