0
0
JavaProgramBeginner · 2 min read

Java Program to Sort Characters in String

To sort characters in a string in Java, convert the string to a char array, use Arrays.sort() on the array, then create a new string from the sorted array with new String(charArray).
📋

Examples

Inputhello
Outputehllo
Inputjava
Outputaajv
Input
Output
🧠

How to Think About It

To sort characters in a string, first think of the string as a list of letters. You can change the string into a list (array) of characters, then arrange that list in order from smallest to largest using sorting. Finally, join the sorted characters back into a string.
📐

Algorithm

1
Get the input string.
2
Convert the string into a character array.
3
Sort the character array using a built-in sorting method.
4
Create a new string from the sorted character array.
5
Return or print the sorted string.
💻

Code

java
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);
    }
}
Output
ehllo
🔍

Dry Run

Let's trace the input "hello" through the code

1

Convert string to char array

input = "hello" -> chars = ['h', 'e', 'l', 'l', 'o']

2

Sort the char array

chars before sort: ['h', 'e', 'l', 'l', 'o'] -> after sort: ['e', 'h', 'l', 'l', 'o']

3

Create new string from sorted chars

sorted = "ehllo"

4

Print the sorted string

Output: ehllo

IterationChar 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

Using StringBuilder and Collections.sort
java
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());
    }
}
This approach uses a list and Collections.sort, which is more flexible but less efficient than sorting a char array.
Using streams (Java 8+)
java
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);
    }
}
This uses Java streams for a concise and modern approach but may be less clear for beginners.

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.

ApproachTimeSpaceBest 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
💡
Use Arrays.sort() on a char array for the simplest and fastest way to sort string characters in Java.
⚠️
Beginners often try to sort the string directly without converting it to a char array first, which is not possible.