reverse array java code example

Example 1: reverse array in java

int length = array.length;
		for(int i=0;i<length/2;i++) {
			int swap = array[i];
			array[i] = array[length-i-1];
			array[length-i-1] = swap;
		}
or
Collections.reverse(Arrays.asList(array));

Example 2: how to reverse a list in java

List<String> stringList = Arrays.asList("A", "B", "C");
    Collections.reverse(stringList);
    assertThat(stringList).containsExactly("C", "B", "A");

Example 3: java how to reverse an array

int length = array.length;
		for(int i=0;i<length/2;i++) {
			int swap = array[i];
			array[i] = array[length-i-1];
			array[length-i-1] = swap;
		}

Example 4: reverse array java

// reverse array

for(int i=intArray.length-1;i>=0;i--)
         System.out.print(intArray[i] + "  ");

Example 5: 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] + " ");  
        }  
    }  
}

Example 6: reverse string array java

//java program to reverse array using for loop
public class ReverseArrayDemo 
{
   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] + " ");  
      }
   }
}

Tags: