Java Program to Sort Characters in String
Arrays.sort() on the array, then create a new string from the sorted array with new String(charArray).Examples
How to Think About It
Algorithm
Code
import java.util.Arrays; public class SortStringChars { public static void main(String[] args) { String input = "hello"; char[] chars = input.toCharArray(); Arrays.sort(chars); String sorted = new String(chars); System.out.println(sorted); } }
Dry Run
Let's trace the input "hello" through the code
Convert string to char array
input = "hello" -> chars = ['h', 'e', 'l', 'l', 'o']
Sort the char array
chars before sort: ['h', 'e', 'l', 'l', 'o'] -> after sort: ['e', 'h', 'l', 'l', 'o']
Create new string from sorted chars
sorted = "ehllo"
Print the sorted string
Output: ehllo
| Iteration | Char Array State |
|---|---|
| Initial | ['h', 'e', 'l', 'l', 'o'] |
| After sort | ['e', 'h', 'l', 'l', 'o'] |
Why This Works
Step 1: Convert string to char array
Using toCharArray() breaks the string into individual characters so they can be sorted.
Step 2: Sort characters
The Arrays.sort() method arranges the characters in ascending order based on their Unicode values.
Step 3: Create sorted string
A new string is made from the sorted character array to get the final sorted string.
Alternative Approaches
import java.util.*; public class SortStringCharsAlt { public static void main(String[] args) { String input = "hello"; List<Character> charList = new ArrayList<>(); for(char c : input.toCharArray()) { charList.add(c); } Collections.sort(charList); StringBuilder sorted = new StringBuilder(); for(char c : charList) { sorted.append(c); } System.out.println(sorted.toString()); } }
import java.util.stream.*; public class SortStringCharsStream { public static void main(String[] args) { String input = "hello"; String sorted = input.chars() .sorted() .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); System.out.println(sorted); } }
Complexity: O(n log n) time, O(n) space
Time Complexity
Sorting the characters takes O(n log n) time where n is the string length, due to the sorting algorithm.
Space Complexity
Converting the string to a char array uses O(n) space; sorting is done in-place on this array.
Which Approach is Fastest?
Sorting the char array with Arrays.sort() is fastest and simplest compared to using lists or streams.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Arrays.sort(char[]) | O(n log n) | O(n) | Simple and fast sorting |
| Collections.sort(List | O(n log n) | O(n) | When working with collections |
| Streams with sorted() | O(n log n) | O(n) | Modern Java style, concise code |
Arrays.sort() on a char array for the simplest and fastest way to sort string characters in Java.