Java – Sorting characters alphabetically in a String


Could smb please explaing the process of sorting characters of String alphabetically? For example, if I have String "hello" the output should be "ehllo" but my code is doing it wrong.

public static void main(String[] args)
        String result = "";
        Scanner kbd = new Scanner(;
        String input = kbd.nextLine();

        for(int i = 1; i < input.length(); i++)
            if(input.charAt(i-1) < input.charAt(i))
                result += input.charAt(i-1);
            //  result += input.charAt(i);


Best Solution

You may do the following thing -

1. Convert your String to char[] array.
2. Using Arrays.sort() sort your char array

Code snippet:

String input = "hello";
char[] charArray = input.toCharArray();
String sortedString = new String(charArray);

Or if you want to sort the array using for loop (for learning purpose) you may use (But I think the first one is best option ) the following code snippet-

char[] charArray = input.toCharArray();
length = charArray.length();

for(int i=0;i<length;i++){
   for(int j=i+1;j<length;j++){
      if (charArray[j] < charArray[i]) {
          char temp = charArray[i];