java

How to Reverse an Array in Java

In this tutorial, we are going to see different ways to reverse an array in Java. For example, if we have an array that contains 1, 2, 3, 4, 5, 6 the program will reverse the array and the result will be 6, 5, 4, 3, 2, 1.
 

Method 1 to reverse an array in Java:

This algorithm goes through the elements of the array and exchanges these elements until it reaches the midpoint.

import java.util.Arrays;
 
public class Main {
  public static void main(String[] args) {
 
    int[] arr = {1, 2, 3, 4, 5, 6};
    System.out.println("Array before inversion:"+ Arrays.toString(arr));
 
    for(int i=0; i< arr.length/2; i++){
        int tmp = arr[i];
        arr[i] = arr[arr.length-i-1];
        arr[arr.length-i-1] = tmp;
    }
    System.out.println("Array after inversion: " + Arrays.toString(arr));
  }
}

Output:

Array before inversion: [1, 2, 3, 4, 5, 6]
Array after inversion: [6, 5, 4, 3, 2, 1]

 

 

Method 2 to reverse an array in Java using Collections.reverse(list):

This method reverses the elements of a specified list. Therefore, we first convert the array to a list using the java.util.Arrays.asList(array) method, and then reverse the list.

import java.util.*; 
  
public class Main { 
  public static void main(String[] args) 
  { 
     Integer [] arr = {1, 2, 3, 4, 5, 6}; 
     System.out.println("Array before inversion:"+ Arrays.toString(arr));
     Collections.reverse(Arrays.asList(arr)); 
     System.out.println("Array after inversion: " + Arrays.asList(arr));
  } 
}

Output:

Array before inversion: [1, 2, 3, 4, 5, 6]
Array after inversion: [6, 5, 4, 3, 2, 1]
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *