Table of contents
1.
Introduction
2.
Problem Statement
3.
Reverse an Array in Java
4.
Approaches
5.
Using Temp array
5.1.
Java
6.
Using Swapping
6.1.
Java
7.
Using Recursion
7.1.
Java
8.
Using Collections.reverse() method
8.1.
Java
9.
Using StringBuilder.append() method
9.1.
Java
10.
Frequently Asked Questions
10.1.
Can you reverse an array in Java?
10.2.
What is the reverse method of an array?
10.3.
What is the time complexity of Collections.reverse() method?
10.4.
How to reverse array in Java using the Java 8 Stream API?
11.
Conclusion
Last Updated: Aug 4, 2024

Reverse Array in Java

Author Tanay kumar Deo
3 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Arrays are a fundamental data structure in programming, offering a way to store and manage collections of elements efficiently. In Java, arrays play a crucial role, often serving as the backbone for handling lists of data. Among the many operations you can perform on arrays, one of the most common and essential tasks is reversing the order of elements. Whether you're preparing for coding interviews, optimizing algorithms, or simply enhancing your problem-solving skills, understanding how to reverse an array is a valuable technique. In this blog, we'll explore various methods to reverse an array in Java.

Reverse Array in Java

Also Read About, Multithreading in java, and Duck Number in Java.

Problem Statement

Write a program to reverse array in Java using different methods. We need to write the Java program to reverse an arrayin using different methods given an input array. 

For Example:

Input:

arr = {10, 20, 30, 60, 50}

 

Output:

{ 50, 60, 30, 20, 10 }     // Reversed array

 

Explanation:

In the example above we should reverse array in java and then print the array in the reversed order.

Reverse an Array in Java

Reversing an array is a common task in programming, which involves rearranging the elements of the array such that the first element becomes the last, the second element becomes the second last, and so on. There are several ways to achieve this in Java, each with its own advantages. Here, we'll explore three primary methods: using a temporary array, the iterative approach, and utilizing built-in utilities.

Approaches

  • Using Temp array
  • Using Swapping
  • Using Recursion
  • Using Collections.reverse() method
  • Using StringBuilder.append() method

Using Temp array

We can reverse array in Java with the help of another temp array. The algorithm for this method is as follows:

  • Take input the size and elements of the array.
  • Write a function reverseArray that takes the parameters: the array(say arr) and its size (say n).
  • In the function, we initialize a new array of size n. We then iterate the array arr[] from the first element, and every element of array arr[] is placed in the temp array from the back, i.e., the temp array is iterated from its last element.
  • In this way, every element of the array arr[] is placed reversely in the temp array.
  • Further, we can iterate through the temp array from the beginning and print all the array elements.

Code:

  • Java

Java

// Reverse array in Java

public class CodingNinjas {

   // Function to reverse array in Java
   static void reverseArray(int arr[], int n)
   {
      int[] temp = new int[n];
      int j = n;
      for (int i = 0; i < n; i++) {
          temp[j - 1] = arr[i];
          j = j - 1;
      }

      // Print the reversed array
      System.out.print("The reversed array is: \n");
      for (int k = 0; k < n; k++) {
          System.out.print(temp[k] + ", ");
      }
   }

   public static void main(String[] args)
   {
      int [] arr = {10, 20, 30, 60, 50};
      reverseArray(arr, arr.length);
   }
}
You can also try this code with Online Java Compiler
Run Code

The above code showed us how to reverse an array in java by using a temp array. The output for the above code is displayed below.

Output

Time Complexity = O(n) because we are iterating over the array length to reverse the array. 

Space Complexity = O(n) since we are using a new array of the same size.

Using Swapping

This method uses a similar code for the inputs and outputs of the array. However, we don't need to create a new array like the previous method. Instead, we reverse the original array itself. The working of this method is described below:

  • Take inputs (similar to the above method).
  • Write a function reverseArrayBySwapping that takes the parameters: the array(say arr) and its size (say n).
  • In the function, we will swap all the elements of the array. The last element is swapped with the first element. The second last element is swapped with the second element and so on. For example, we swap arr[0] with arr[n-1], arr[1] with arr[n-2], … and so on.
  • In this way, every element of the array arr[] is swapped.
  • Finally, we can iterate through the array from the beginning and print all the array elements.

Code:

  • Java

Java

// Java program to reverse an array

public class CodingNinjas{

   // Function to reverse array in Java by swapping the array
   static void reverseArrayBySwapping(int arr[], int n){
         int i, k, t;
         for (i = 0; i < n / 2; i++) {
           t = arr[i];
           arr[i] = arr[n - i - 1];
           arr[n - i - 1] = t;
         }

         // Print the reversed array
       System.out.print("The reversed array is: \n");
       for (k = 0; k < n; k++) {
             System.out.print(arr[k] + ", ");
         }
   }

   public static void main(String[] args)
   {
       int[] arr = { 10, 20, 30, 60, 50 };
       reverseArrayBySwapping(arr, arr.length);
   }
}
You can also try this code with Online Java Compiler
Run Code


The above code showed us how to reverse an array in java by swapping the elements. The output for the above code is displayed below.

Output

Time Complexity = O(n) because we are iterating over the half of array(n/2) for swapping.

Space Complexity = O(1) as we have initiated some constant variables only.

Using Recursion

In this method, we will use recursion to swap the elements of the array for reversing it. The working of this method is listed below:

  • Take inputs.
  • Write a function reverseArrayByRecursion that takes the parameters: the array(say arr) and indexes to be swapped, i.e. start and end.
  • In the function, we will swap arr[start] with arr[end] and recursively call the function again by incrementing the start value by one and decrementing the end value by 1. The function will return or exit(i.e. Base condition of recursion) if start> end. 
  • In this way, every element of the array arr[] is swapped.
  • Finally, we can iterate through the array from the beginning and print all the array elements. 

Code:

  • Java

Java

// Java program to reverse an array using Recursion

public class CodingNinjas{

   // Function to reverse array in Java by swapping the elements
   static void reverseArrayByRecursion(int arr[], int start, int end){
          int t;
   if(start > end)
               return;
       else {
   t = arr[start];
    arr[start] = arr[end];
    arr[end] = t;
  }
           reverseArrayByRecursion(arr, start+1, end-1);
    }

   public static void main(String[] args)
   {
       int[] arr = { 10, 20, 30, 60, 50 };
                int k, n=arr.length;
       reverseArrayByRecursion(arr, 0, n-1);


         // Print the reversed array
       System.out.println("The reversed array is: \n");
       for (k = 0; k < arr.length; k++) {
           System.out.print(arr[k] + ", ");
         }
   }
}
You can also try this code with Online Java Compiler
Run Code

The above code showed us how to reverse an array in java by swapping the elements of the array using the recursion method. The output for the above code is displayed below.

Output

Time Complexity = O(n) because the recursive function will be called n/2 times.

Space Complexity = O(n) because we recursively call to reverse function n/2 times and the stack size is n/2

Also, see Introduction to Javascript

Using Collections.reverse() method

This method uses Java.util.Collections.reverse(List list) method. This method reverses the elements in the given list. Hence, we first convert the array into a list by using  Java.util.Arrays.asList(array), and then we will reverse the list. 

Code:

  • Java

Java

// Java program to reverse an array using Collections.reverse() method

import java.util.*;

public class CodingNinjas{

   // Function to reverse array in Java
   static void reverseAsList(Integer a[])
   {
         Collections.reverse(Arrays.asList(a));
         System.out.println(Arrays.asList(a));
   }

   public static void main(String[] args)
   {
         Integer [] arr = {10, 20, 30, 60, 50};
         reverseAsList(arr);
   }
}
You can also try this code with Online Java Compiler
Run Code

The above code is a java program to reverse an array by converting the array in a List and then using Collections.reverse(Arrays.asList(arr)). The output for the above code is displayed below.

Output

Time Complexity = O(n) since Collection.reverse() method has a time complexity of O(n)

Space Complexity = O(1) as we have not initiated any extra variables.

Practice it on online java compiler for better understanding.

Must Read  C Program to Reverse a Number

Using StringBuilder.append() method

This method is helpful, if we are working with any String array, we may use a StringBuilder and append every array element using a for loop decrementing from the array’s length (say n), finally convert the StringBuilder to a string, and then split back into an array.

  • Java

Java

// Java program to reverse an array

import java.util.*;

class CodingNinjas {
   public static void main(String[] args) {
         Integer [] arr = {10, 20, 30, 60, 50};
         String[] strArray = new String[arr.length];

         // Converting Int array to String Array
         for (int i = 0; i < arr.length; i++) {
             strArray[i] = String.valueOf(arr[i]);
       }
     
       StringBuilder reversedArray = new StringBuilder();
     
       for (int i = strArray.length; i > 0; i--) {
             reversedArray.append(strArray[i - 1]).append(" ");
       }
     
       String[] reversed = reversedArray.toString().split(" ");
       System.out.println(Arrays.toString(reversed));
     
   }
}
You can also try this code with Online Java Compiler
Run Code

The above code is a java program to reverse an array by converting the array in a StringBuilder and then using StringBuilder.append() method. The output for the above code is displayed below.

Output

Time Complexity = O(n) because we are iterating over the array length for converting the int array to string array and appending it to the reversedArray StringBuilder.

Space Complexity = O(n) as we have extra arrays like reversed, strArray of size n each. 

Also check out Addition of Two Numbers in Java here.

Frequently Asked Questions

Can you reverse an array in Java?

Yes, you can reverse an array in Java using an iterative approach to swap elements or by using a temporary array.

What is the reverse method of an array?

Java does not have a built-in array reverse method; however, you can use Collections.reverse() for arrays of objects after converting to a List.

What is the time complexity of Collections.reverse() method?

Collections.reverse() method will reverse the elements of the ArrayList in linear time i.e its time complexity is O(n).

How to reverse array in Java using the Java 8 Stream API?

We can also invert an array by using the Java 8 Stream API:

Object[] invertUsingStreams(Object[] arr) {

     return IntStream.rangeClosed(1, arr.length)

      .mapToObj(i -> array[array.length - i])

      .toArray();

}

Conclusion

In this article we have extensively discussed how to reverse array in Java using different methods like using temp array, using swapping, using recursion, using Collections.reverse() method and Using StringBuilder.append() method. We hope that this blog has helped you enhance your knowledge on how to reverse an array in java. To learn more about Data Structures and Algorithms, you can enroll in our course on DSA in Java

Live masterclass