How to sort array elements alphabetically in Java?

Hello Tech Aspirants, I hope you are doing well.
In this tutorial, we will learn how to sort array elements in alphabetical order using Java.
We will take a simple example to understand the concept of to perform our task. So continue reading it…

Constraints

  • A string may contain any number of characters.
  • We will perform sorting on the basis of the indexing
  • It will start checking from 1st and if 2 strings matches with the first index it will move to the next index.

Java Code to sort array elements alphabetically

  • Input the strings to be sorted and store them in name[].
  • Take the loop i starting from 0 to the last number of string.
    by taking the j loop from n+1 we can able to traverse the whole loop by putting the previous value(i=0 in 1st case) constant.
    by using compareTo function we can compare two strings(one as constant and other traversing 1 step ahead to the last) lexicographically.
    If the compared string is equal, this method returns 0 otherwise returns positive(first string is lexicographically greater than the second string) and negative values(first string is lexicographically smaller than the second string).
  • Print the reordered string.
import java.util.Scanner;
class sort_alphabetically
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter The number of String to be entered");
int n=sc.nextInt();
String name[]=new String[n];
Scanner sc1=new Scanner(System.in);
System.out.println("Enter the names");
  for(int i=0;i<n;i++)
      {
        name[i]=sc1.nextLine();
      }
      for (int i=0;i<n;i++)
        {
            for (int j=i+1;j<n;j++)
            {
                if (name[i].compareTo(name[j])>0)
                {
                    String temp=name[i];
                    name[i]=name[j];
                    name[j]=temp;
                }
            }
        }
        System.out.println("Names in arranged order are:-");
        for(int i=0;i<n;i++)
        {
            System.out.println(name[i]);
        }
}
}

Output

The output of our java program will look something like you can see below:

Enter The number of String to be entered
5
Enter the names
Sanskar
Aakash
Satyam
Sameer
Abhinav
Names in arranged order are:-
Aakash
Abhinav
Sameer
Sanskar
Satyam

Also read: How to Fetch Random Line From a Text File In Java

 

We can see that the output showing elements with alphabetical order. So we are successfully able to sort our array elements alphabetically with Java program.

Hope this tutorial helped you.

One response to “How to sort array elements alphabetically in Java?”

  1. Facebook says:

    Any tech enthusiast who wants to learn how to sort array elements in alphabetical order with Java, this article from Sanskar is the right place for you.

Leave a Reply

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