Java Program to sort string in alphabetical order


In this program, You will learn how to sort string in alphabetical order in Java.


Enter a string: bcb

Alphabetical order: bbc


Example: How to sort string in alphabetical order in Java

Run it Now
import java.util.Scanner;

class Main {
    public static void main(String args[]) {

        Scanner sc = new Scanner(System.in);
        String str;

        System.out.print("Enter a String :");
        str = sc.nextLine();

        int i, j;
        char temp;

        char ch[] = str.toCharArray();
        int l = ch.length;

        for (i = 0; i < l; i++) {
            for (j = i + 1; j < l; j++) {
                if (ch[i] > ch[j]) {
                    temp = ch[i];
                    ch[i] = ch[j];
                    ch[j] = temp;
                }
            }
        }

        String str1 = String.valueOf(ch);
        System.out.print("\nSorted String :" + str1);
    }
}

Output:

Enter a String :sam
Sorted String :ams