how to display array backwards in java code example

Example 1: Reverse an array in java using for loop

// Reverse an array in java using for loop
public class ReverseArrayUsingForLoop 
{
   public static void main(String[] args) 
   {
      int[] arrNumbers = new int[]{2, 4, 6, 8, 10};  
      System.out.println("Given array: ");  
      for(int a = 0; a < arrNumbers.length; a++)
      {
         System.out.print(arrNumbers[a] + " ");
      }
      System.out.println("Reverse array: ");
      // looping array in reverse order
      for(int a = arrNumbers.length - 1; a >= 0; a--) 
      {  
         System.out.print(arrNumbers[a] + " ");  
      }
   }
}

Example 2: java code to reverse an array

public class ReverseArray {  
    public static void main(String[] args) {  
        //Initialize array  
        int [] arr = new int [] {1, 2, 3, 4, 5};  
        System.out.println("Original array: ");  
        for (int i = 0; i < arr.length; i++) {  
            System.out.print(arr[i] + " ");  
        }  
        System.out.println();  
        System.out.println("Array in reverse order: ");  
        //Loop through the array in reverse order  
        for (int i = arr.length-1; i >= 0; i--) {  
            System.out.print(arr[i] + " ");  
        }  
    }  
}

Tags:

Java Example