Online Tutorials & Training Materials | STechies.com
Register Login

3 Methods to Reverse an Array in Java

|| || 0

3 Methods to Reverse an Array in Java
Stechies

What is Array Reverse in Java?

To implement array reverse in Java Programming, the array size and thereafter the array elements have to be entered by the user. In the next step, the array elements are swapped. A variable (temp) of the same type is created for placing the first element in variable temp, then the element coming last is placed in the first, temp is placed in the last, and so forth – the process continues till the entire array is reversed.

In Java, mostly primitive types of arrays - int, long, string and double arrays – are required to be reversed for the purpose of specific codes. Apache commons lang, which is an open source library attributed to the Apache software foundation, provides class ArrayUtils. This interesting class is used in association with the java.util.Arrays class for playing with object and primitive arrays in Java.  The API provides easy-to-use overloaded methods for reversing different types of arrays in Java – be it int, log, double, float or object arrays.

Read on to know about this and other methods pertaining to how to reverse an array in java – the right way.

Reverse an Array in Java How to Reverse Array in Java with Examples

There are many methods to reverse an array in Java. You may consider writing a function on your own that loops across the array and keep swapping all the elements until the full array is sorted. In another method of array reverse in Java, an array can be converted into an ArrayList, after which a specific code can be used for reversing the ArrayList. Yet another method of array reverse in Java comprises of using the Apache Commons ArrayUtils.reverse() program for the sake of reversing any kind of Java array. This method can be overloaded for the cause of reversing short, long, int, byte, float, double or string type arrays.  Users may like to implement any method to reverse an array in java as per their choice and nature of the array in the reckoning.

Method 1: Reverse Array in Place

In this simple means of reversing a Java array, the algorithm is made to loop over the array and keeps swapping the elements until the midpoint is reached. As no additional buffers are used, this method of reversing an array in Java is also referred to as an array in-place.

for(int i=0; i<array.length/2; i++){

 int j= array[i];

 array[i] = array[array.length -i -1];

 array[array.length -i -1] = j;

}

The time complexity of the above algorithm is O(n/2). In other words, it is O(N) as the iteration across the loop takes place till its midpoint only. This method provides an ideal solution for interviewees as the remaining two methods are apt for practical purposes.

Method 2 - Using an ArrayList

This particular method of array reverse in Java converts the given array into an ArrayList and then utilizes the Collections.reverse() method that takes up the items in the list and reverses the elements in linear time. Arrays of int, string or other types can be reversed with the help of this method.The following example depicts a reversal of a string type array in Java:

//Simple Java Program to reverse a string array

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collections;

import java.util.List;

public class ArrayReverse {

   public static void main(String args[])  {

     String[] arrayColor = {"Red", "Green", "Blue", "Orange","Yellow"};

     System.out.println("Array Before: " + Arrays.toString(arrayColor) );

     List<String> arrayNewColor = Arrays.asList(arrayColor);      

     Collections.reverse(arrayNewColor);

     String[] reversed = arrayNewColor.toArray(arrayColor);

     System.out.println("Array Reverse: " + Arrays.toString(reversed) );

   }

}

Output

Array Before: [Red, Green, Blue, Orange, Yellow]

Array Reverse: [Yellow, Orange, Blue, Green, Red]

As is evident from the output provided above, the original order of elements has been reversed in the final array as returned by the toArray() method of the List class.

Method 3 - By using ArrayUtils.reverse()

Apache commons refers is a collection of numerous utility libraries used for effective Java development. This library is often added by default by coders to their projects with a view of complementing JDK. The Apache Commons Lang offers class ArrayUtils that comprises of overloaded reverse() methods for the cause of reversing int, float as well as object type arrays in Java. This particular method reverses any given array in its place; in other words, a new array is not created for the purposes of array reverse in the Java code.

The following code will aptly depict this method:

import java.util.Arrays;

import org.apache.commons.lang3.ArrayUtils;

public class Byarrayutilis {

   public static void main(String args[]) {

       String[] arraycolor = {"Red", "Green", "Blue", "Orange","Yellow"};

       System.out.println("Array before: " + Arrays.toString(arraycolor));

       ArrayUtils.reverse(arraycolor);

       System.out.println("Array after: " + Arrays.toString(arraycolor));

   }

}

Output

Array Before: [Red, Green, Blue, Orange, Yellow]

Array Reverse: [Yellow, Orange, Blue, Green, Red]

The ArrayUtils class belongs to Apache Commons Lang. Commons-lang3-3.4.jar has to be added into the application's class path for this method to take place. Alternatively, in the case of Maven is being used then the following dependency has to be included in the pom.xml file.

<dependency>

       <groupId>org.apache.commons</groupId>

       <artifactId>commons-lang3</artifactId>

       <version>3.4</version>

   </dependency>

How do I Print reverse of an array in Java?

At the very onset, values have to be provided to the array that needs to be reversed in Java.

int[] var = { 1, 2, 3 };

Next, the loop counter has to be initialized. This initialization process can take place from within the loop structure. The loop can be defined as:

for (int i = var.length - 1; i >= 0; --i){

System.out.println(var[i]);

}

The output is 321 that will be printed to the console.

Conclusion

The above-mentioned methods go a long way in helping coders reverse int & String array in Java. Reverse array in Java can be appropriately implemented in line with the above three methods. In case you have to answer an interview question pertaining to a java program to reverse an array then use the in-place algorithm. The others methods include usage of the ArrayList class and the utility method ArrayUtils.reverse() belonging to the Apache commons lang library. Choose the method that applies to your reverse array in java programming needs in the best possible way!

 


Related Articles

0.0106 seconds.