Java Program to Reverse an Array
Explanation
This program demonstrates how to reverse an array in Java. We will use a simple algorithm that swaps elements from the beginning of the array with elements from the end of the array. The process continues until we reach the middle of the array.
Code
/**
* This Java program reverses an array.
* It demonstrates the basic concept of swapping elements in an array.
*/
public class ReverseArray {
/**
* The main method is the entry point of the program.
* It initializes an array, prints it, reverses it, and then prints the reversed array.
*
* @param args Command-line arguments (not used in this program).
*/
public static void main(String[] args) {
// Initialize the array
int[] array = {1, 2, 3, 4, 5};
// Print the original array
System.out.println("Original Array:");
printArray(array);
// Reverse the array
reverseArray(array);
// Print the reversed array
System.out.println("Reversed Array:");
printArray(array);
}
/**
* This method reverses the given array in place.
* It swaps elements from the beginning and end of the array until the middle is reached.
*
* @param array The array to be reversed.
*/
public static void reverseArray(int[] array) {
int start = 0; // Starting index
int end = array.length - 1; // Ending index
// Loop until start index is less than end index
while (start < end) {
// Swap the elements at start and end
int temp = array[start];
array[start] = array[end];
array[end] = temp;
// Move the start index forward and end index backward
start++;
end--;
}
}
/**
* This method prints the elements of the given array.
*
* @param array The array whose elements are to be printed.
*/
public static void printArray(int[] array) {
for (int i : array) {
System.out.print(i + " ");
}
System.out.println();
}
}
Explanation of the Code
Class Definition:
The ReverseArray
class contains all the methods required to reverse an array and print it.
Main Method:
The main
method initializes an array, prints the original array, calls the reverseArray
method to reverse the array, and then prints the reversed array.
reverseArray Method:
The reverseArray
method takes an array as input and reverses it in place. It uses two pointers: start
(initialized to the beginning of the array) and end
(initialized to the end of the array). The elements at these positions are swapped, and the pointers are moved towards the center. This process continues until the start index is less than the end index.
printArray Method:
The printArray
method takes an array as input and prints its elements. This is used to display the array before and after reversing it.