How to sort a string array in java

Let’s learn how to sort a string array in java.

Sort a string array

Basically String class do not have method to sort string array. In java, to sort string array we need to match each element of an array to the remaining elements. Then, if result is > 0 we have to swap them.

Let’s see a java program using nested for loop. In this nested for loop, inner loop starts with a + 1, where “a” is the variable of “outer for loop”.

import java.util.Arrays;

public class SortStringArray
{
   public static void main(String[] args) 
   { 
      String strPlaces[] = {"Great Barrier Reef", "Paris", "BoraBora", "Florence","Tokyo", "Cusco"};
      int size = strPlaces.length;
      for(int a = 0; a < size - 1; a++) 
      {
         for(int b = a + 1; b < strPlaces.length; b++) 
         {
            if(strPlaces[a].compareTo(strPlaces[b]) > 0) 
            {
               String temp = strPlaces[a];
               strPlaces[a] = strPlaces[b];
               strPlaces[b] = temp;
            }
         }
      }
      System.out.println(Arrays.toString(strPlaces));
   }
}



Output:

how to sort a string array in java

Using Arrays.sort() method

Arrays.sort() method sorts the specified array of objects into ascending order according to the natural ordering of its elements.

Here’s the java program,

import java.util.Arrays;

public class JavaArraySort
{
public static void main(String[] args)
{
String strGiven[] = {"Great Barrier Reef", "Paris", "borabora", "Florence","tokyo", "Cusco"};
Arrays.sort(strGiven);
System.out.println("Output(case sensitive) : " + Arrays.toString(strGiven));
}
}



Output:

Output(case sensitive) : [Cusco, Florence, Great Barrier Reef, Paris, borabora, tokyo]


Also read – preface to java virtual machine and architecture