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.

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("Sorted string:" + str1);
    }
}

Output:

Enter a string:xiith
Sorted string:hiitx