Array Java Programs

Reverse Array without using Second Array or inplace Reversal

In this tutorial, we will learn to write a Java program to invert an array without using another array. This is also known as inplace array reversal program in Java.

In the previous tutorial we have seen array reversal in Java using second array.

Inplace Array reversal Program in Java

import java.util.*;

public class ArrayExample {
	public static void main(String[] args) {
		int startIndex, lastIndex;
		Scanner sc = new Scanner(System.in);
		System.out.print("Enter the size of array: ");
		int size = sc.nextInt();
		int arr[] = new int[size];
		for (int i = 0; i < size; i++) {
			System.out.print("Please give value for index " + i + " : ");
			arr[i] = sc.nextInt();
		}
		startIndex = 0;
		lastIndex = size - 1;
		while (startIndex < lastIndex) {
			arr[startIndex] = arr[startIndex] + arr[lastIndex];
			arr[lastIndex] = arr[startIndex] - arr[lastIndex];
			arr[startIndex] = arr[startIndex] - arr[lastIndex];
			startIndex++;
			lastIndex--;
		}
		System.out.println("Array After Reversing :");
		for (int i = 0; i < size; i++) {
			System.out.println(arr[i]);
		}
	}
}

Output

Enter the size of array: 5
Please give value for index 0 : 1
Please give value for index 1 : 2
Please give value for index 2 : 3
Please give value for index 3 : 4
Please give value for index 4 : 5
Array After Reversing :
5
4
3
2
1

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs