Java Program to Reverse an Array - The Coding Shala

Home >> Java Programs >> Reverse an Array

 In this post, we will learn how to Reverse an Array in Java.

Java Program to Reverse an Array

You have given an Array, Write a Java Program to Reverse the given array.

Example 1:
Input: arr = {1,2,3,4,5}
Output: arr = {5,4,3,2,1}

Approach 1

We can use an extra array to store the elements in reverse order then copy all the elements into the original array.

The alternate way is we can swap elements in the same array. For example, swap the first element with the last element, swap the second element with the second last element and continue.

Java Program: 

// Java program to Reverse an Array

public class Main {
	
	public static void main(String[] args) { 
		
		int[] arr = {1, 2, 3, 4, 5};
		
		System.out.println("Before Reverse array is: ");
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
		System.out.println();
		
		// swap ith and length-ith element
		for (int i = 0; i < arr.length / 2; i++) {
			int temp = arr[i];
			arr[i] = arr[arr.length - i - 1];
			arr[arr.length - i - 1] = temp;
		}
		
		// print array
		System.out.println("Reversed Array is: ");
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
	}
}

Output: 

Before Reverse array is: 
1 2 3 4 5 
Reversed Array is: 
5 4 3 2 1 


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Anti Diagonals - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

LeetCode - Bulb Switcher Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala