Java Example - Array Reversal
In the following example, we use a custom reverse method to reverse the array:
Example 1
public class tutorialproTest {
/* Reverse array */
static void reverse(int a[], int n)
{
int[] b = new int[n];
int j = n;
for (int i = 0; i < n; i++) {
b[j - 1] = a[i];
j = j - 1;
}
/* Print reversed array */
System.out.println("Reversed array is: \n");
for (int k = 0; k < n; k++) {
System.out.println(b[k]);
}
}
public static void main(String[] args)
{
int [] arr = {10, 20, 30, 40, 50};
reverse(arr, arr.length);
}
}
The output of the above code is:
Reversed array is:
50
40
30
20
10
Example 2
public class tutorialproTest {
/* Create a method to swap the first with the last, the second with the second last, and so on */
static void reverse(int a[], int n)
{
int i, k, t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
System.out.println("Reversed array is: \n");
for (k = 0; k < n; k++) {
System.out.println(a[k]);
}
}
public static void main(String[] args)
{
int [] arr = {10, 20, 30, 40, 50};
reverse(arr, arr.length);
}
}
The output of the above code is:
Reversed array is:
50
40
30
20
10
Example
import java.util.*;
public class tutorialproTest {
/* Using java.util.Arrays.asList(array) method */
static void reverse(Integer a[])
{
Collections.reverse(Arrays.asList(a));
System.out.println(Arrays.asList(a));
}
public static void main(String[] args)
{
Integer [] arr = {10, 20, 30, 40, 50};
reverse(arr);
}
}
The output of the above code is:
[50, 40, 30, 20, 10]