java sort string characters alphabetically

Let’s learn java sort string characters alphabetically.

java sort string characters alphabetically

To sort string characters alphabetically String class do not have any method. So we are using different methods to sort string characters alphabetically.

So here the first method we are applying is toCharArray() method. This method converts given string to a new character array.

Another method is sort() method of Arrays class. This method sorts the given character array in ascending order.

Before final step we have to create new String to store alphabetically sorted string characters. Because we know String is immutable in java.

Finally use String class constructor to create sorted string that contains the characters of the character array.

Here’s the java code to arrange the letters of a string in alphabetical order.

import java.util.Arrays;
public class CharactersAlphabetically
{
   public static void main(String[] args)
   {
      String strInput = "flowerbrackets";
      // converting string to char array
      char[] ch = strInput.toCharArray();
      // sorting char array
      Arrays.sort(ch);
      // converting char array to string
      String strSorted = String.valueOf(ch);
      System.out.println("sort string characters alphabetically: " + strSorted);
   }
}


Output:

sort string characters alphabetically: abceefklorrstw


Also read – polymorphism in java