Sort String in Ascending Order in Java

1. Introduction

Sorting a string in ascending order involves rearranging its characters alphabetically from 'a' to 'z' and 'A' to 'Z'. This can be useful in various programming contexts, such as data processing, text analysis, or when implementing custom sorting mechanisms. This tutorial will demonstrate how to sort the characters of a string in ascending order using Java.

Key Points

- Sorting is done by converting the string to a character array.

- The array is then sorted using the Arrays.sort() method from the Java Arrays class.

- The sorted array is converted back to a string.

2. Program Steps

1. Convert the string to a character array.

2. Sort the character array.

3. Convert the sorted character array back to a string.

4. Print the sorted string.

3. Code Program

import java.util.Arrays;

public class SortString {
    public static void main(String[] args) {
        // Input string
        String input = "java";
        // Convert input string to character array
        char[] chars = input.toCharArray();
        // Sort the character array
        Arrays.sort(chars);
        // Convert the sorted array back to a string
        String sortedString = new String(chars);
        // Output the sorted string
        System.out.println("Sorted String: " + sortedString);
    }
}

Output:

Sorted String: aajv

Explanation:

1. String input = "java": Declares and initializes the input string.

2. char[] chars = input.toCharArray(): Converts the input string into a character array for sorting.

3. Arrays.sort(chars): Sorts the character array in ascending order using the Arrays.sort() method.

4. String sortedString = new String(chars): Converts the sorted character array back into a string.

5. System.out.println("Sorted String: " + sortedString): Prints the sorted string to the console.


Comments