View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Reversing an Array in Java

Updated on 01/04/20259,854 Views

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. 

  • In-place with a for loop: The most effective and straightforward approach. 
  • Collections.reverse(): Perfect for ArrayList instances. 
  • A new array: Generates a backward copy of the initial array. 
  • Java 8 Stream: Beneficial for functional programming styles. 
  • Recursion: A neater yet less efficient approach regarding memory consumption. 

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.

What is Array Reversal?

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.

Real World Applications

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: 

  • Two-Pointer Approach
  • Java Collections (Collections.reverse())
  • Temporary Array
  • Recursion
  • Stream API
  • Stack

Also Read: How to do Reverse String in Java?

Reverse an Array Using a Temporary Array

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:

  • Generate a new temporary array that matches the size of the original array. 
  • Iterate through the initial array and transfer the elements into the temporary array in the opposite sequence. 
  • Transfer the items from the temporary array to the original array. 

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

Reverse an Array In-Place Using Two-Pointer Approach

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: 

  • Set up two pointers: 
    • Start: Indicates the initial item of the array. 
    • end: Refers to the final element of the array. 
  • As long as start is smaller than end: 
  • Exchange the items at the beginning and the conclusion. 
  • Increase the start pointer and reduce the end pointer. 
  • The array will undergo reversal when the pointers converge or intersect. 

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): 

  • Sets up two pointers: start (indicates the first element) and end (indicates the last element). 
  • Utilizes a while loop to exchange the elements at the beginning and end, then advances the start and reduces the end to progress toward the array's center. 
  • The loop persists until the start pointer is no longer smaller than the end pointer. 

printArray(int[] array): 

  • A straightforward auxiliary function to display the elements of the array 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

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. 

Reverse an Array Using Recursion

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:

  • This approach utilizes recursion to reverse the array. 
  • It exchanges the elements at the positions start and end, subsequently invoking itself recursively with the next pair of indices (start + 1 and end - 1), thereby progressively reducing the sub-array that is being reversed. 
  • The recursion halts when start is greater than or equal to end, serving as the base case. 

printArray Method: 

  • This technique displays the array both 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

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. 

Reverse an Array Using Collections Framework

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:

  • Transforming the array into a List: Initially, we change the array into a List<Integer> since Collections.reverse() operates on lists. We iterate over the array and append each element to the list. 
  • Reversing the List: The Collections.reverse() function changes the sequence of the items in the list. 
  • Transforming the List back into an array: After the reversal, we iterate through the list and transfer the elements back into the original array. 

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

Difference Between Iterative and Recursive Array Reversal

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.

Iterative Approach:

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

Recursive Approach:

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
}

Common Mistakes and Best Practices in Array Reversal

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

  1. Incorrect swap index: Mixing up indices (e.g., using arr.length - i instead of arr.length - i - 1) leads to errors.
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;
}
  1. Skipping elements: Failing to run the loop only until the midpoint of the array can leave some elements unreversed.
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.
  1. Using the wrong loop boundaries: Off-by-one errors in loop conditions can cause out-of-bounds exceptions.
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;
}
  1. Not using a temporary variable: Trying to swap without a temporary variable can overwrite data unintentionally.
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
}
  1. Overlooking empty or single-element arrays: Special cases (array of length 0 or 1) might cause unexpected behavior if not handled.
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;
}
  1. Mixing array references when using a temp array: Accidentally assigning indices incorrectly between the original and temporary arrays can lead to confusion or incorrect outputs.
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:

  1. Use Two-Pointer Swapping: In-place reversal with two pointers (start and end) avoids extra space and is efficient for large arrays.
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.
  1. Verify Loop Boundaries: Only iterate until the middle to swap elements correctly and avoid overwriting data.
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.
  1. Handle Special Cases: Consider edge cases like empty arrays or single-element arrays to prevent errors.
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.
  1. Prefer Iteration Over Recursion: Iteration avoids the additional overhead and stack usage of recursive calls.
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;
}
  1. Use Collections for Object Arrays: Converting an object array to a List and using Collections.reverse() can simplify the process (not for primitives).
// 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]
  1. Mind Performance: All these methods generally run in O(n) time, so the simplest loop-based in-place technique is usually best.
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

Common Interview Questions on Array Reversal

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

Practice Exercise Suggestion

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.

Exercise 1: Reverse an Array in Java

Write a program to reverse the elements of an array in Java.

Implementation Process:

  1. Initialize an array with some elements (e.g., integers).
  2. Create a method (e.g., reverseArray()) that takes the array as a parameter and reverses its elements in place.
  3. Swap the elements:
    • Use two pointers/index variables (start and end).
    • Swap the elements at the start and end positions.
    • Increment start and decrement end until they meet or cross.
  4. Print the reversed array to verify the result.

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

  • Array Declaration In the main method, an integer array numbers is created and initialized with example values.

ReverseArray Method

  • The reverseArray(int[] array) method performs the in-place reversal.
  • It uses two pointers: start at the beginning (index 0) and end at the last index (array.length - 1).
  • Elements at these positions are swapped, after which the start is incremented and the end is decremented.
  • This process continues until the start meets or exceeds the end, ensuring all elements have been reversed.

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

Exercise 2: Reverse an Array Using a New Array

Goal

Instead of reversing the array in place, use a separate array to store the reversed elements.

Implementation Steps

  1. Initialize the original array (e.g., numbers).
  2. Create a second array (reversedArray) with the same length.
  3. Copy elements from the original array into the new array in reverse order.
  4. Print the reversed array to confirm the results.
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

  1. Before any reversal
    The original array is:
    10 20 30 40 50
  2. During the loop
    For each index i, you are taking the element from the end of the original array (numbers.length - 1 - i) and placing it in the front of reversedArray[i].

Concretely:

  • When i = 0, reversedArray[0] gets the value from numbers[4] which is 50.
  • When i = 1, reversedArray[1] gets the value from numbers[3] which is 40.
  • …and so forth.
  1. End result
    • The reversedArray becomes:
      50 40 30 20 10

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.

Exercise 3: Reverse an Array Using Recursion

Goal

Practice recursion by creating a function that reverses an array using a method that calls itself.

Implementation Steps

  1. Write a recursive method that takes the array, a start index, and an end index as parameters.
  2. Swap the elements at the start and end indices.
  3. Recursively call the method with start incremented and end decremented.
  4. Stop when start >= end.

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

  1. Before reversal
    The original array is:
    5 10 15 20 25 30
  2. Recursive swapping
    The reverseRecursive(arr, 0, arr.length - 1) call starts with start = 0 and end = 5.
    First swap: Swap elements at indices 0 and 5 → 5 ↔ 30  
    Array becomes: 30 10 15 20 25 5
    Second swap: Next recursive call is with start = 1, end = 4 → 10 ↔ 25  
    Array becomes: 30 25 15 20 10 5
    Third swap: Next call is start = 2, end = 3 → 15 ↔ 20  
    Array becomes: 30 25 20 15 10 5
    Base case: Once the start reaches or exceeds the end, recursion stops.
  3. End result
    The final array is reversed in place:
    30 25 20 15 10 5

Output

Original Array: 5 10 15 20 25 30
Reversed Array: 30 25 20 15 10 5

Exercise 4: Implement a Method That Reverses a Portion of An Array

Goal

Reverse only a specific section of an array while keeping the rest unchanged.

Implementation Steps

  1. Initialize an array with values.
  2. Define the start and end indices for the portion to be reversed.
  3. Swap elements within this range using a two-pointer approach.
  4. Print the modified array to verify the results.

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

  1. The program starts by defining an integer array with seven elements.
  2. Two integer variables, start and end, specify the portion of the array to reverse (from index 2 to 5).
  3. A while loop is used to perform the reversal.
  4. The loop runs as long as start is less than end.
  5. Inside the loop:
    1. The element at start is temporarily stored in a variable.
    2. The element at end is assigned to start.
    3. The temporarily stored value is assigned to end.
    4. Both start is incremented, and end is decremented to move toward the center.
  6. The process continues until the two pointers meet or cross each other.
  7. After the loop completes, the modified array is printed, ensuring only the selected portion has been reversed.

Explanation of the Output

  1. Before reversal, the original array is: 10 20 30 40 50 60 70
  2. During the swapping process:
    1. First swap: Element at index 2 (30) swaps with element at index 5 (60).
      1. The array becomes: 10 20 30 60 40 50 30 70 
    2. Second swap: Element at index 3 (40) swaps with element at index 4 (50).
      1. The array becomes:10 20 60 50 40 30 70
  3. After reversal, the final modified array is: 10 20 60 50 40 30 70
  4. The output confirms that only the elements between indices 2 and 5 have been reversed while the rest of the array remains unchanged.
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

Conclusion

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:

FAQ 

1. What is the best way to reverse an array in Java?

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.

2. Can we reverse an array without using extra space?

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.

3. Is recursion efficient for reversing an 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.

4. How do I reverse a specific portion of an array?

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.

5. Does Java provide a built-in method to reverse an array?

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.

6. What is the time complexity of array reversal methods?

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.

7. How do I reverse an array in a single line of code?

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.

8. How do I reverse an array in Java 8 using streams?

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.

9. What are some additional programming languages in which array reversal is essential?

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.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

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.