sort word in string array in java code example

Example 1: How to sort a string array in java

// how to sort string array in java without using sort method
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));
   }
}

Example 2: How to sort a string array in java

// java program to sort an array using Arrays.sort() method
import java.util.Arrays;
public class JavaArraySortMethod
{
   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));
   }
}

Tags:

Java Example