How can I sort a String in Java?

Hi Priyanka,

One simple approach to sort a string is to convert the string into a character array, use Arrays.sort() to sort the characters, and then convert it back into a string. Here’s how you can do it:

import java.util.Arrays;

public class SortString {
    public static void main(String[] args) {
        String s = "edcba";
        char[] charArray = s.toCharArray(); // Convert string to character array
        Arrays.sort(charArray); // Sort the character array
        String sortedString = new String(charArray); // Convert back to string
        System.out.println(sortedString); // Output: abcde
    }
}

Explanation:

  1. toCharArray() converts the string to a character array.
  2. Arrays.sort() sorts the array alphabetically.
  3. Then, you can easily convert the sorted character array back into a string.
  4. This is one of the most straightforward ways to java sort string alphabetically.