Java Example – Sort String Array




Java Tutorial for Beginners
Java Tutorial for Beginners

In this Java Example we will learn How To sort String array (Array of string values) in java, use Arrays.sort method. Array.sort is method is a static method and Sorts the specified array of objects into ascending order, according to the {Comparable natural ordering} of its elements.
One this to note here is, by default Arrays.sort method sorts the Strings in case sensitive manner. To sort an array of Strings irrespective of case, use Arrays.sort(String[] strArray, String.CASE_INSENSITIVE_ORDER) method instead.

/**
 * String array in java by codebind.com.
 */
import java.util.Arrays;

public class SortStringArray {

    public static void main(String args[]){

        //String array
        String[] strNames = new String[]{"Lina", "alina", "Tom", "Jack", "harry", "Ram"};

        //sort String array using sort method
        Arrays.sort(strNames);

        System.out.println("String array sorted (CASE SENSITIVE ORDER)");

        //print sorted elements
        for(int i=0; i < strNames.length; i++){
            System.out.println(strNames[i]);
        }

        
        //case insensitive sort
        Arrays.sort(strNames, String.CASE_INSENSITIVE_ORDER);

        System.out.println("String array sorted (CASE INSENSITIVE ORDER)");
        //print sorted elements again
        for(int i=0; i < strNames.length; i++){
            System.out.println(strNames[i]);
        }

    }
}

/*
Output :
String array sorted (CASE SENSITIVE ORDER)
Jack
Lina
Ram
Tom
alina
harry
String array sorted (CASE INSENSITIVE ORDER)
alina
harry
Jack
Lina
Ram
Tom
*/

 
 





Partner Sites

VideoToGifs.com

EasyOnlineConverter.com

SqliteTutorials.com





Be the first to comment

Leave a Reply

Your email address will not be published.


*