Reverse Of An Array In Java

6 min read

Reversing an array in Java means arranging its elements in the opposite order, so the first element becomes the last, the second becomes the second-to-last, and so on. The most efficient approach uses two index variables that move toward each other while swapping elements, requiring only constant extra memory and completing in linear time Simple, but easy to overlook..

Introduction

An array stores a fixed number of values in contiguous positions that can be accessed by numeric indexes. In Java, indexing begins at 0, while the final valid index is array.length - 1.

  • Index 0 exchanges values with the final index.
  • Index 1 exchanges values with the index immediately before the final position.
  • This continues until both index variables meet near the center.

As an example, reversing [10, 20, 30, 40, 50] produces [50, 40, 30, 20, 10]. The original array can be modified directly, or a separate reversed copy can be created. Choosing between these options depends on whether the original order must be preserved.

Reversing an Array In Place

The preferred method for most situations is the two-pointer technique. That said, one pointer starts at the beginning of the array, while the other starts at the end. After each swap, the pointers move one position toward the center.

public class ArrayReverseExample {

    public static void reverse(int[] values) {
        if (values == null) {
            throw new IllegalArgumentException("Array must not be null");
        }

        int left = 0;
        int right = values.length - 1;

        while (left < right) {
            int temporary = values[left];
            values[left] = values[right];
            values[right] = temporary;

            left++;
            right--;
        }
    }

    public static void main(String[] args) {
        int[] numbers = {5, 10, 15, 20, 25};

        reverse(numbers);

        for (int number : numbers) {
            System.out.print(number + " ");
        }
    }
}

Output:

25 20 15 10 5

Don't overlook the condition left < right. It ensures that every pair is swapped once. It carries more weight than people think. When the pointers become equal, they refer to the middle element of an odd-length array, which does not need to move. If they cross, previously reversed pairs would be swapped again and the array would return toward its original order That's the part that actually makes a difference..

The official docs gloss over this. That's a mistake Small thing, real impact..

This method changes the original array. After calling reverse(numbers), the previous ordering is no longer available unless it was stored elsewhere And it works..

Step-by-Step Algorithm

The in-place algorithm can be expressed in a simple sequence:

  1. Create a left variable and assign it 0.
  2. Create a right variable and assign it array.length - 1.
  3. Continue while left is smaller than right.
  4. Save the value at the left index in a temporary variable.
  5. Copy the value at the right index into the left position.
  6. Copy the temporary value into the right position.
  7. Increase left by one and decrease right by one.
  8. Stop when the pointers meet or cross.

A temporary variable is necessary because assigning one array position directly to another would overwrite a value that still needs to be moved That's the part that actually makes a difference. That's the whole idea..

Scientific Explanation of the Two-Pointer Method

The correctness of the algorithm can be understood through a loop invariant. Now, at the beginning of every iteration, all positions before left and all positions after right already contain their final reversed values. The unprocessed section lies between the two pointers.

Each iteration places two elements into their correct final positions. Which means, the correctly reversed portion grows by two elements. The loop stops when no unprocessed pair remains Easy to understand, harder to ignore..

Only half of the array requires explicit processing. An array with n elements needs approximately n / 2 swaps:

  • Four elements require two swaps.
  • Five elements require two swaps; the center remains fixed.
  • Eight elements require four swaps.

An empty

Edge‑case handling

The algorithm works flawlessly for most inputs, but it is worth examining the corner cases that often trip developers.

  • Empty array – when values contains zero elements, values.length equals 0, so right becomes -1. The initial comparison left < right evaluates to false, causing the while loop to be skipped entirely. The array stays unchanged, which is the expected behaviour.

  • Single‑element array – here left starts at 0 and right at 0. Because left is not less than right, the loop never executes, leaving the lone element in place. No extra work is required.

  • Two‑element array – the pointers start at opposite ends (0 and 1). One exchange occurs, after which left becomes 1 and right becomes 0, breaking the loop condition. The two values are now reversed.

These examples illustrate that the core logic automatically adapts to arrays of any size without extra special‑case code.


Time and space analysis

The algorithm touches each element at most once per pointer movement, resulting in a linear running time of O(n) where n is the number of elements. Still, since only a constant amount of additional storage—namely a single temporary variable—is used, the auxiliary space consumption is O(1). This makes the method ideal for embedded systems or other memory‑constrained environments where allocating extra buffers would be undesirable.

Because the operation is performed in place, it preserves the original object identity. Any subsequent code that relies on the mutability

...of the original array remains valid, which is crucial when other parts of the program hold references to the same data structure. That said, this mutability also means the method is not thread-safe by default; concurrent reads during the swap process could observe inconsistent intermediate states unless external synchronization is applied Easy to understand, harder to ignore..

From a practical standpoint, the two-pointer reversal serves as a building block for more complex in-place transformations, such as rotating arrays or implementing certain cryptographic permutations. When working with large datasets that exceed cache lines, the sequential access pattern from both ends toward the center exhibits excellent spatial locality, often outperforming recursive approaches that suffer from stack overhead Worth knowing..

While the algorithm is optimal for primitive arrays and mutable collections, immutable data structures

While the algorithm is optimal for primitive arrays and mutable collections, immutable data structures require a different strategy. Here's the thing — in languages that favor immutability—such as Haskell, Scala, or modern JavaScript with const‑declared arrays—reversing a sequence typically means producing a new collection rather than altering the existing one. A straightforward functional approach is to fold the input from left to right, prepending each element to an accumulator; this yields a reversed copy in linear time and linear auxiliary space because the accumulator grows with each step Still holds up..

When the underlying runtime supports lazy evaluation, one can also generate a reversed view on demand. As an example, a lazy sequence that indexes the original array as original[n‑1‑i] provides O(1) access to the reversed order without materializing a new array, preserving both time efficiency and the immutability contract. On the flip side, such views depend on the original collection remaining unchanged for the lifetime of the view, which shifts the responsibility of synchronization to the caller Still holds up..

In practice, the choice between an in‑place two‑pointer swap and an immutable reversal hinges on the surrounding codebase’s mutability guarantees and performance constraints. Here's the thing — if the array is owned exclusively by a single thread and memory is at a premium, the in‑place method remains the go‑to solution. Conversely, when sharing data across components or when functional purity is valued, allocating a new reversed array—or employing a lazy reversed view—offers safety and composability at the cost of additional allocation or indirect access Practical, not theoretical..

In a nutshell, the two‑pointer technique provides an optimal, in‑place reversal for mutable arrays, handling edge cases naturally and delivering O(n) time with O(1) extra space. For immutable contexts, developers can either create a new reversed copy or take advantage of lazy views, trading off allocation or indirection for adherence to immutability principles. Selecting the appropriate variant depends on the specific requirements of thread safety, memory usage, and API design within the application Took long enough..

New This Week

What's New Today

If You're Into This

Topics That Connect

Thank you for reading about Reverse Of An Array In Java. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home