java

How to Sort a String Alphabetically in Java?

In this tutorial, we are going to see how to sort a string alphabetically in Java.

In the following example, we ask the user to enter the number of names they want to enter for the sort. Once the number is captured using the Scanner class, we initialized an array of names with the size of the input number, then run a for loop to capture all the strings entered by the user.

Once we have all the names stored in the array of names, we match the first alphabet of each name to sort them in alphabetical order.
 

 

Java Program to Sort a String alphabetically:
import java.util.Scanner;

public class Main
{
    public static void main(String[] args) 
    {
        int nbr;
        String tmp;
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number of names you want to enter : ");
        nbr = scanner.nextInt();
		
        String names[] = new String[nbr];
        Scanner scanner1 = new Scanner(System.in);
        System.out.println("Enter the list of names:");
		
        for(int i=0; i < nbr; i++)
        {
            names[i] = scanner1.nextLine();
        }
        for (int i=0; i < nbr; i++) 
        {
            for (int j=i+1; j < nbr; j++) 
            {
                if (names[i].compareTo(names[j]) > 0) 
                {
                    tmp = names[i];
                    names[i] = names[j];
                    names[j] = tmp;
                }
            }
        }
        System.out.print("List of names in sorted order is : ");
        for (int i=0; i < nbr-1; i++) 
        {
            System.out.print(names[i] + ",");
        }
        System.out.print(names[nbr - 1]);
    }
}

Output:

Enter the number of names you want to enter : 3
Enter the list of names:
Bob
Ali
Thomas
List of names in sorted order is : Ali, Bob, Thomas
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *