Java program to sort names in an alphabetical order

Let’s learn java alphabetical sort or java program to sort names in an alphabetical order.

Java program to sort names in an alphabetical order

Java sort strings alphabetically is one of the common java interview question. Now let’s learn java sort alphabetically.

  • In java sort alphabetically java program first user enters number of strings in arranging strings in an alphabetical order.
  • In the next step number of strings is stored in integer variable using Scanner class.
  • Then for loop is used to store all the strings entered by user. Finally compare first letter of each string to store in alphabetical order.

Also read – bubble sort in java

Here’s how to sort strings alphabetically in java,

// sort strings alphabetically
import java.util.Scanner;
public class SortStringArray 
{
   public static void main(String[] args)
   {
      int number;
      String str;
      Scanner sc1 = new Scanner(System.in);
      System.out.print("Please enter number of strings : ");
      number = sc1.nextInt();
      String players[] = new String[number];
      Scanner sc2 = new Scanner(System.in);
      System.out.println("Enter all strings : ");
      for(int a = 0; a < number; a++)
      {
         players[a] = sc2.nextLine();
      }
      for(int a = 0; a < number; a++)
      {
         for(int b = a + 1; b < number; b++)
         {
            if(players[a].compareTo(players[b]) > 0) 
            {
               str = players[a];
               players[a] = players[b];
               players[b] = str;
            }
         }
      }
      System.out.print("In sorted order : ");
      for(int a = 0; a < number - 1; a++) 
      {
         System.out.print(players[a] + ", ");
      }
      System.out.print(players[number - 1]);
      sc1.close();
      sc2.close();
   }
}

Output:

java program to sort names in an alphabetical order