Java program to sort string array in an alphabetical order

Hey guys!! Welcome to flower brackets blog. In this post we are going to learn java program to sort string array in an alphabetical order.

Java program to sort string array in an alphabetical order

  • In this 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 – sort string array java

Java program for sorting characters alphabetically in a string,

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 string array in an alphabetical order

Related Posts