Java Example – Program to reverse an array or string




Java Tutorial for Beginners
Java Tutorial for Beginners
Java Tutorial for Beginners
Java Tutorial for Beginners

 

In this Java example we will see how to Reverse String Array. the example below shows how to sort an array of String in Java using Arrays and Collections classes.
There are basically two ways we can Reverse String Array, first is to use temporary array and manually loop over the elements of an Array and swap them or second way is to use Arrays and Collections classes. This example uses the second approach.

/**
 * Created by codebind.com.
 */
import java.util.Collections;
import java.util.List;
import java.util.Arrays;

public class ReverseStringArray {

    public static void main(String args[]){

        //String array
        String[] strNames = new String[]{"Max", "Tom", "Mark", "John"};

        //create a list from String array
        List<String> list = Arrays.asList(strNames);

        //reverse the list using Collections.reverse method
        Collections.reverse(list);

        //convert the list back to String array
        strNames = (String[]) list.toArray();

        System.out.println("reversed String array ");

        //print the reversed String array
        for(int i=0; i < strNames.length; i++){
            System.out.println(strNames[i]);
        }

    }

}

/*
Output :
reversed String array 
John
Mark
Tom
Max
*/

 
 





Partner Sites

VideoToGifs.com

EasyOnlineConverter.com

SqliteTutorials.com





Be the first to comment

Leave a Reply

Your email address will not be published.


*