Reverse Array in Java: Explanation & Practice

Reverse an array in place

Problem summary

Write a program that reverses an array. Your code should work for ANY array.

Starter code

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5}; // Test case 1
        
        // Reverse array in place
        // Print elements space-separated
    }
}

Expected output and test cases

  • Reverse [1,2,3,4,5]
    5 4 3 2 1
  • Reverse [1,2,3,4]
    4 3 2 1
  • Reverse [1]
    1

Hints

  1. Swap elements from both ends
  2. Use two pointers: start and end
  3. Stop when pointers meet in middle

Related Arrays exercises

Practice all Arrays exercises · Run this idea in the Java compiler