Java Program to Sort Strings in Alphabetical Order

Write a Java program to sort strings alphabetical order. This Java example allows entering the size and string items. Next, we used the Java Array sort function to sort the strings or or string arrays in alphabetical order.

package RemainingSimplePrograms;

import java.util.Arrays;

import java.util.Scanner;

public class SortStringArrAlphabetically1 {
	private static Scanner sc;
	private static Scanner sc2;
	public static void main(String[] args) {
		
		sc = new Scanner(System.in);
		sc2 = new Scanner(System.in);
		
		System.out.print("Enter the Total Strings you enter = ");
		int Size = sc.nextInt();
		
		String str[] = new String[Size];
		
		System.out.format("Enter %d Strings one by one\n", Size);
		for(int i = 0; i < Size; i++) 
		{
			str[i] = sc2.nextLine();
		}
		
		Arrays.sort(str);
		
		System.out.format("\nAfter Sorting the String Alphabetically\n");
		for(String s: str) 
		{
			System.out.print(s + "  ");
		}
	}
}
Java Program to Sort Strings in Alphabetical Order

Java Program to Sort Strings in Alphabetical Order using a for loop

In this Java example, we used the for loop to iterate the string array from start to end and compare each string with another string. We used the temp variable to move their places based on the result.

package RemainingSimplePrograms;

import java.util.Scanner;

public class SortStringArrAlphabetically2 {
	private static Scanner sc;
	private static Scanner sc2;
	public static void main(String[] args) {
		int Size, i, j;
		String temp;
		
		sc = new Scanner(System.in);
		sc2 = new Scanner(System.in);
		
		System.out.print("Enter the Total Strings you enter = ");
		Size = sc.nextInt();
		
		String str[] = new String[Size];
		
		System.out.format("Enter %d Strings one by one\n", Size);
		for(i = 0; i < Size; i++) 
		{
			str[i] = sc2.nextLine();
		}
		
		for(i = 0; i < Size; i++) 
		{
			for(j = i + 1; j < Size; j++)
			{
				if(str[i].compareTo(str[j]) > 0)
				{
					temp = str[i];
					str[i] = str[j];
					str[j] = temp;
				}
			}
		}
		
		System.out.format("\nAfter Sorting the String Alphabetically\n");
		for(i = 0; i < Size; i++) 
		{
			System.out.print(str[i] + "  ");
		}
	}
}
Enter the Total Strings you enter = 5
Enter 5 Strings one by one
banana
kiwi
apple
usa
canada

After Sorting the String Alphabetically
apple  banana  canada  kiwi  usa