Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Problem Statement
3.
Using Temp array
4.
Using Swapping
5.
Using Recursion
6.
Using Collections.reverse() method
7.
Using StringBuilder.append() method
8.
FAQs
9.
Key Takeaways
Last Updated: Mar 27, 2024

Reverse Array in Java

Author Tanay Kumar
3 upvotes
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

A good programmer is one who can write optimized code. To develop this ability, we should have knowledge of data structures and algorithms. Because of this reason, the knowledge of DSA (Data Structures and Algorithms) is frequently tested in interviews for Software Development Engineering (SDE) roles. The importance of DSA cannot be emphasized enough, especially if we aim to get placed in product-based companies like Facebook, Amazon, Google, Microsoft, Adobe, etc. 

For questions related to each data structure, refer to the blog Must-Do Coding Interview Questions for Product Based Companies.

In this blog, we will discuss the various methods to reverse Array in Java. So, let’s get started with the article and learn how to reverse an 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.

In this blog, we are going to solve this problem using the following approaches:

  • Using Temp array
  • Using Swapping
  • Using Recursion
  • Using Collections.reverse() method
  • Using StringBuilder.append() method
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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:

// 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);
    }
}

 

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 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);
    }
}


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 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] + ", ");
                  }
    }
}

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 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);
    }
}

 

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 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));
        
    }
}

 

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.

FAQs

  1. Among all the listed methods, which algorithm is most efficient to reverse array in Java?
    The time complexity of all the methods is O(N) and the space complexity of all the algorithms except Using temp array and Using StringBuilder.append() method is constant. So they all are equally efficient i.e. they all have O(N) time complexity.
     
  2. What is StringBuilder in java?
    StringBuilder in Java represents the mutable sequence of characters. String Class in Java creates the immutable sequence of any character, the StringBuilder class provides the alternative to String Class, as it creates the mutable sequence of characters.
     
  3. 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).
     
  4. 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();
}

Key Takeaways

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

Happy Coding!

Live masterclass