Ad Code

Sorting Names in Alphabetical using Java.

 Sorting Names in Alphabetical 

In this tutorial, we will learn how to sort names in alphabetical order using Java programming language. We will use the Arrays class provided by Java to sort the names.

PROGRAM :-

 // Java Program to Sort Names in an Alphabetical Ordering
class sortingnames 
{
    public static void main(String[] args)
    {
        // storing input in variable
        int n = 4;
        // create string array called names
        String names[]
            = { "Rahul", "Ajay", "Gourav", "Riya" };
        String temp;
        for (int i = 0; i < n; i++) 
   {
            for (int j = i + 1; j < n; j++) 
            {
                // to compare one string with other strings
                if (names[i].compareTo(names[j]) > 0) 
                {
                    // swapping
                    temp = names[i];
                    names[i] = names[j];
                    names[j] = temp;
                }
            }
        }
        // print output array
        System.out.println(
            "The names in alphabetical order are: ");
        for (int i = 0; i < n; i++) 
        {
            System.out.println(names[i]);
        }
    }
 }

OUTPUT :-

The names in alphabetical order are: 

Ajay

Gourav

Rahul

Riya


:: Share this tutorial post with your friends.

Post a Comment

0 Comments

Ad Code