Sort Characters in a String in Java — Definition, Examples and Program

Learn how to sort characters in a string in Java using a simple comparison-based approach without using built-in sorting utilities.

Sort Characters in a String in Java

Sorting characters in a string means arranging all characters in a specific order (usually ascending order based on ASCII values).

This program helps understand character comparison, loops, and basic sorting logic without relying on library methods.

Understanding the Problem

Given a string, we need to:

Example 1

Input: programming

Output: aggimmnoprr

Example 2

Input: Java

Output: Jaa v → (ASCII sorted) → Jaav

Logic Explanation

  1. Convert the string to a character array.
  2. Use two nested loops to compare characters.
  3. Swap characters if they are in the wrong order.
  4. Continue until all characters are sorted.

Java Program to Sort Characters in a String


import java.util.Scanner;

public class SortCharacters {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a string: ");
        String str = sc.nextLine();

        char[] ch = str.toCharArray();

        for (int i = 0; i < ch.length - 1; i++) {
            for (int j = i + 1; j < ch.length; j++) {
                if (ch[i] > ch[j]) {
                    char temp = ch[i];
                    ch[i] = ch[j];
                    ch[j] = temp;
                }
            }
        }

        System.out.print("Sorted string: ");
        for (char c : ch) {
            System.out.print(c);
        }
    }
}

Sample Output


Enter a string: programming
Sorted string: aggimmnoprr

Important Notes

Practice Challenges

  1. Modify the program to sort characters in descending order.
  2. Ignore spaces while sorting characters.
  3. Sort characters without converting to a character array.

This program builds a strong foundation in string manipulation and sorting algorithms in Java.