In this tutorial, you will learn how to reverse integer array. Here, we have created a method to reverse an array which has been passed as a parameter and returns a new array with all the elements in reverse order. In the main method, we have allowed the user to enter numbers and invoked the method.
Example:
import java.util.*;
class ReverseArray{
public static int [] reverse (int a[]){
for ( int i = 0 ; i < a.length/2 ; i++ ){
int temp = a[i] ;
a[i] = a[a.length-i-1] ;
a[a.length-i-1] = temp ;
}
return a;
}
public static void main(String[] args)
{
int a[]=new int[5];
Scanner input=new Scanner(System.in);
System.out.println("Enter five array elements: ");
for(int i=0;i<a.length;i++){
a[i]=input.nextInt();
}
int array[]=reverse(a);
System.out.println("Array In Reverse Order: ");
for(int i=0;i<array.length;i++){
System.out.println(array[i]);
}
}
}
Output:
Enter five array elements: 3 5 6 2 4 Array In Reverse Order: 4 2 6 5 3
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.