Java Program to sort the strings in alphabetical order

February 2, 2022, Learn eTutorial

Here we are explaining how to write a java program to sort the strings in alphabetical order. So first we have to read the number of strings the user wants to sort into a variable. Then we have to read the strings into an array. By using a for loop we can compare the strings and place it into the proper positions.

How to compare strings in java?

We can compare the strings in java by using the method compareTo(). An example of compareTo() is shown below.

StringA.compareTo(StringB) where StringA and StringB are strings.

The function compareTo() return a value zero if both the strings are equal. If StringA is greater than the StringB then the function returns a positive value.

If StringA is less than the StringB, then the function returns a negative value.

How to implement the java program to sort the strings in alphabetical order?

First, we have to declare the class Sortstr with a public modifier. Then open the main() function. Then read the number of strings the user wants to enter into the variable n. Read the strings into the array str[i] using a for a loop.Then by using nested for loop ,compare str[i] with str[j].If str[i] is greater than str[j] then change the position. After that display the elements in the array str[] using for loop.


STEP 1: Declare the class Sortstr with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: Declare the variable n as integer,t as a string.

STEP 4: Read the number of strings into the variable n.

STEP 5: Declare the string array str[] of size n.

STEP 6: By using a for loop with the condition i

STEP 7: By using another for loop with the condition j

STEP 8: compare the string str[i] with str[j].If true then interchange str[i] with str[j].

STEP 9: Increment j by one do step 7.

STEP 10: Display the sorted string as the elements in str[i] using for loop.


Java Source Code

                                          import java.util.Scanner;
public class SortStr
    public static void main(String[] args) 
        int n;
        String t;
        Scanner sc = new Scanner(;
        System.out.print("Enter number of strings:");
        n= sc.nextInt();
        String str[] = new String[n];
        Scanner sc1 = new Scanner(;
        System.out.println("Enter the Strings :");
        for(int i = 0; i < n; i++)
            str[i] = sc1.nextLine();
        //sort the strings
        for (int i = 0; i < n; i++) 
            for (int j = i + 1; j < n; j++) { 
                if (str[i].compareTo(str[j])>0) 
                    t = str[i];
                    str[i] = str[j];
                    str[j] = t;
        System.out.print("Sorted strings:");
        for (int i = 0; i <= n- 1; i++) 


Enter number of strings:4
Enter the Strings :

Sorted Strings: