How to reverse Integer Array in Java


Here is the reverse the integer array in java,


 public class Reverse {  
      static int array[] = { 1, 2, 3, 4, 5 };  
      public static void main(String args[]) {  
           System.out.println("Before Reverse");  
           for (int i = 0; i < array.length; i++) {  
                System.out.print(array[i]+" ");  
           }  
           for (int i = 0; i < array.length / 2; i++) {  
                int temp = array[i];  
                array[i] = array[array.length - i - 1];  
                array[array.length - i - 1] = temp;  
           }  
           System.out.println("\n");  
           System.out.println("After Reverse");  
           for (int i = 0; i < array.length; i++) {  
                System.out.print(array[i]+" ");  
           }  
      }  
 }  


Output:

Before Reverse
1 2 3 4 5

After Reverse
5 4 3 2 1

0 comments:

Post a Comment