java tutorial - How to sort string array in Java - java programming - learn java - java basics - java for beginners



sort string array in java

Learn java - java tutorial - Sort string array in Java - java examples - java programs

Sort String Array in Java :

  • In Arrays, “Array.sort” is a static method and then it sorts the specified array of objects into ascending order, along with 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 a array of strings regardless of case, make use of these methods Arrays.sort(String[] strArray, String.CASE_INSENSITIVE_ORDER) as a substitute.

sample code:

import java.util.Arrays;
 
public class kaashiv_infotech
{
 
    public static void main(String args[])
    {
         String[] strvalues = new String[]{"anitha", "arjun", "manoj", "Jimy", "hari", "Ragu","sai"};
          Arrays.sort(strvalues);
 
        System.out.println("String array sorted (CASE SENSITIVE ORDER)");
         for(int i=0; i < strvalues.length; i++){
            System.out.println(strvalues[i]);
        }
        Arrays.sort(strvalues, String.CASE_INSENSITIVE_ORDER);
         System.out.println("String array sorted (CASE INSENSITIVE ORDER)");
          for(int i=0; i < strvalues.length; i++){
            System.out.println(strvalues[i]);
        }
 
    }
}

Output:

String array sorted (CASE SENSITIVE ORDER)
Jimy
Ragu
anitha
arjun
hari
manoj
sai
String array sorted (CASE INSENSITIVE ORDER)
anitha
arjun
hari
Jimy
manoj
Ragu
sai

Related Searches to How to sort string array in Java