Java Online Compiler
Example: Reverse Array In-Place (Swapping Elements) in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Reverse Array In-Place (Swapping Elements) import java.util.Arrays; // Required for Arrays.toString() public class Main { public static void main(String[] args) { // Step 1: Declare and initialize the array int[] myArray = {10, 20, 30, 40, 50, 60}; System.out.println("Original Array: " + Arrays.toString(myArray)); // Step 2: Initialize two pointers, one at the start and one at the end int left = 0; int right = myArray.length - 1; // Step 3: Loop until the pointers meet or cross while (left < right) { // Step 4: Swap elements at the left and right pointers int temp = myArray[left]; myArray[left] = myArray[right]; myArray[right] = temp; // Step 5: Move pointers towards the center left++; right--; } // Step 6: Print the reversed array System.out.println("Reversed Array (in-place): " + Arrays.toString(myArray)); } }
Output
Clear
ADVERTISEMENTS