Title: Reverse an Array using a Loop
Reversing an array is one of the first array manipulations every Java developer meets, and it quietly shows up again and again inside bigger problems like palindrome checks, rotation, and in-place reordering. In this guide, you’ll learn how to reverse an array using a simple loop in Java, without allocating a second array. We’ll walk through the algorithm, trace it on a real input, step through examples, call out the mistakes beginners actually make, and finish with the interview follow-ups you should be ready for.
Understanding the Problem
Given an array such as {1, 2, 3, 4, 5}, we want to produce {5, 4, 3, 2, 1}. The order of elements is flipped end to end: the first element becomes the last, the second becomes the second-to-last, and so on. We want to do this in place, which means we modify the original array directly instead of creating a new one. That keeps the extra memory we use at O(1) regardless of the input size.
Approach
The cleanest way to reverse an array in place is the two-pointer technique: one pointer left starts at index 0, another pointer right starts at the last index. We swap the elements they point to, then move the pointers toward each other. When they meet (or cross), every element has been placed in its mirrored position.
- Initialize
left = 0andright = arr.length - 1. - While
left < right, repeat the next three steps. - Save
arr[left]into a temporary variabletemp. - Assign
arr[right]toarr[left]. - Assign
temptoarr[right]. - Increment
leftand decrementright. - When
left >= right, the array is fully reversed.
Java Program
Here is the complete, compilable program that reverses an array using a while loop with the two-pointer swap.
public class ReverseArrayLoop {
public static void reverseArray(int[] arr) {
int left = 0;
int right = arr.length - 1;
while (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
reverseArray(numbers);
System.out.print("Reversed array: ");
for (int num : numbers) {
System.out.print(num + " ");
}
}
}Explanation of the Program
The method reverseArray receives the array by reference, so every write to arr[...] is visible to the caller once the method returns. Inside the method, two local variables left and right hold the indices of the two elements we are about to swap.
- The
whileconditionleft < rightkeeps the loop running until the two pointers meet. The strict less-than is deliberate; swapping an element with itself at the center is a no-op we don’t need to perform. - Inside the loop, the classic three-line swap uses
tempto holdarr[left]while we overwrite it witharr[right]. Withouttemp, we would lose the original value. - After each swap,
left++advances inward from the start andright--advances inward from the end. One iteration moves both ends by one position. - In
main, we create a sample array, callreverseArray, and print the result using an enhancedforloop.
Step-by-Step Trace
Let’s trace the algorithm on the input {10, 20, 30, 40, 50, 60}, where the target output is {60, 50, 40, 30, 20, 10}.
| Iteration | left | right | arr (before swap) | arr (after swap) |
|---|---|---|---|---|
| 1 | 0 | 5 | {10, 20, 30, 40, 50, 60} | {60, 20, 30, 40, 50, 10} |
| 2 | 1 | 4 | {60, 20, 30, 40, 50, 10} | {60, 50, 30, 40, 20, 10} |
| 3 | 2 | 3 | {60, 50, 30, 40, 20, 10} | {60, 50, 40, 30, 20, 10} |
| end | 3 | 2 | loop exits | {60, 50, 40, 30, 20, 10} |
At the end of iteration k, the first k and last k elements of arr are already in their final reversed positions. The untouched middle shrinks by two every iteration, which is why the loop terminates in n/2 steps.
Examples
Example 1: Even-length array
The two pointers cross cleanly at the center without touching any middle element.
int[] arr = {11, 22, 33, 44};
reverseArray(arr);
// Output: {44, 33, 22, 11}Example 2: Odd-length array
The middle element stays in place because once left equals right, the loop condition left < right is false.
int[] arr = {5, 15, 25, 35, 45};
reverseArray(arr);
// Output: {45, 35, 25, 15, 5}Example 3: Single-element array
With one element, right starts at 0, the condition left < right is false immediately, and the array is returned unchanged.
int[] arr = {99};
reverseArray(arr);
// Output: {99}Common Mistakes to Avoid
A short reverse loop looks obvious once you’ve seen it, but the first time around most learners trip on one of these.
- Starting right at arr.length – the first access
arr[arr.length]throwsArrayIndexOutOfBoundsException. Initializeright = arr.length - 1instead. - Looping from 0 to arr.length – a single-pointer
forloop that swapsarr[i]witharr[n - 1 - i]across the whole range swaps every pair twice and leaves the array unchanged. Stop ati < arr.length / 2. - Overwriting without a temp variable – writing
arr[left] = arr[right]before savingarr[left]destroys the left value, and the next line puts the right value back on itself. Use atempvariable orXORonly when you are sure the indices differ. - Using <= in the while condition – when
left == rightyou swap the middle element with itself, which is harmless but wasteful and signals that the intent isn’t clear. Prefer the strictleft < right. - Returning a new reversed array by accident – allocating
int[] result = new int[arr.length]and copying into it works, but it’sO(n)extra memory and the caller still holds the original array unchanged. Mutate the input directly for the in-place version.
Edge Cases to Test
Before you call this method done, walk your implementation through these inputs.
- Empty array
- Single-element array
- Two-element array
- Odd-length array (middle index unchanged)
- Even-length array (pointers cross without touching)
- Array containing duplicate values
- Array containing
Integer.MIN_VALUEorInteger.MAX_VALUE - Null array reference
Additional Considerations
Time complexity: The loop runs n / 2 times, where n is the length of the array. Each iteration does a constant number of operations, so the total cost is O(n).
Space complexity: We only use three extra integer variables (left, right, temp) regardless of input size. That is O(1) auxiliary space – the defining advantage of the two-pointer in-place approach over building a reversed copy.
Null and empty inputs: The method silently handles an empty array because arr.length - 1 is -1, so the while condition is false immediately. A null array, however, throws NullPointerException at arr.length. If the caller might pass null, add a guard that throws IllegalArgumentException so the problem surfaces at the call site rather than inside the loop.
Reference versus primitive arrays: The same loop works for String[], Object[], or any reference array; only the type of temp changes. The swap moves references, not the objects themselves, so no deep copying is involved.
Interview Follow-up Questions
Reversing an array is rarely the end of the interview. Be ready for the natural follow-ups below.
- Can you reverse the array using recursion instead of a loop? – swap
arr[left]witharr[right], then recurse onleft + 1andright - 1; base case isleft >= right. - How would you reverse only a sub-range of the array, say indices l to r? – factor the two-pointer swap into a helper that takes
startandend; the main method then becomesreverse(arr, 0, arr.length - 1). - What if the input is an immutable List and you cannot swap in place? – build a new list in a single reverse-indexed pass, or wrap it with
Collections.reverseon a mutable copy; the time complexity staysO(n)but space becomesO(n). - How would you reverse a singly linked list using the same spirit? – maintain three pointers (
prev,curr,next) and flip each node’s link as you walk through; it is stillO(n)time andO(1)space. - What if the elements arrive as a stream of unknown length and must be printed in reverse? – push each item onto a stack as it arrives, then pop until the stack is empty; this is
O(n)time withO(n)extra space, since you cannot swap in place without random access.
Conclusion
Reversing an array with a loop is a tiny program, but it quietly introduces three ideas you’ll reuse everywhere in Java: the two-pointer pattern, the three-line swap through a temporary variable, and the discipline of mutating in place to keep auxiliary space at O(1). Once you’ve internalized this template, you’ll recognize it inside palindrome checks, array rotation by reversal, and partitioning routines.
Try adapting the code to reverse a String[], to reverse only the second half of an array, or to reverse in place using recursion. You can learn more about array problems and in-place algorithms here: Arrays.



