codescracker


java

Java Program to Sort Strings in Alphabetical Order



« Previous Program Next Program »


Sort Strings

To sort strings in alphabetical order in Java programming, you have to ask to the user to enter the two string, now start comparing the two strings, if found then make a variable say temp of the same type, now place the first string to the temp, then place the second string to the first, and place temp to the second string and continue.

Java Programming Code to Sort Strings in Alphabetical Order

Following Java Program ask to the user to enter any five string like names to sort them in alphabetical order then display the sorted string in alphabetical order on the screen:

/* Java Program Example - Sort Strings */
		
import java.util.Scanner;

public class JavaProgram
{
    public static void main(String[] input)
    {
        int i, j;
        String temp;
        Scanner scan = new Scanner(System.in);
        
        String names[] = new String[5];
		
        System.out.print("Enter 5 Names/Words : ");
        for(i=0; i<5; i++)
        {
            names[i] = scan.nextLine();
        }
		
        System.out.println("\nSorting Words/Names in Alphabetical Order...\n");
        for(i=0; i<5; i++)
        {
            for(j=1; j<5; j++)
            {
                if(names[j-1].compareTo(names[j])>0)
                {
                    temp=names[j-1];
                    names[j-1]=names[j];
                    names[j]=temp;
                }
            }
        }
		
        System.out.print("Words/Names Sorted in Alphabetical Order Successfully..!!");
		
        System.out.println("\nNow the List is :\n");
        for(i=0;i<5;i++)
        {
            System.out.println(names[i]);
        }
    }
}

When the above Java Program is compile and executed, it will produce the following output:

Java Program sort string

Same Program in Other Languages

You may also like to learn and practice the same program in other popular programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test