Java Program to sort the given string Alphabetically

Program

import java.util.Scanner;
import java.util.Arrays;
public class SortStringsAlphabetically {
    public String sortStrings(String string)
    {
        char tempArray[] = string.toCharArray();          
        Arrays.sort(tempArray);
        return new String(tempArray);
    }
    public static void main(String[] args){
        SortStringsAlphabetically sortStringsAlphabetically = new SortStringsAlphabetically();
        Scanner reader = new Scanner(System.in);
        System.out.print("Enter a string to sort: ");
        String enteredString = reader.nextLine();
        String sortedString = sortStringsAlphabetically.sortStrings(enteredString);
        System.out.println("Sorted String is "+ sortedString);                
    }
}

This program sorts the characters of a given string alphabetically.

  1. Input:

    • The program prompts the user to enter a string.
  2. Logic:

    • Convert the string into a character array using toCharArray().
    • Use Arrays.sort() to sort the array of characters in ascending (alphabetical) order.
    • Convert the sorted character array back into a string using new String().
  3. Steps:

    • Read the input string from the user.
    • Convert the string into a character array.
    • Sort the character array.
    • Convert the sorted array back to a string and return it.
  4. Output:

    • The sorted string is displayed to the user.
  5. Key Methods:

    • toCharArray(): Converts the string into an array of characters.
    • Arrays.sort(): Sorts the characters in the array in ascending order.
  6. Example Execution:

    • Input:
      Enter a string to sort: banana
      
    • Process:
      • Convert "banana" into ['b', 'a', 'n', 'a', 'n', 'a'].
      • Sort the array: ['a', 'a', 'a', 'b', 'n', 'n'].
      • Convert back to a string: "aaabnn".
    • Output:
      Sorted String is aaabnn
      
  7. Complexity:

    • Time Complexity: O(n log n) due to the sorting algorithm.
    • Space Complexity: O(n) for the character array.

Features:

  • Case-Sensitivity:
    • Uppercase letters are sorted before lowercase ones due to ASCII values.
    • Example: Input "Banana" → Output: "Baaann".
  • Simple and Efficient:
    • Leverages built-in Java methods for sorting.

Use Case:

  • Useful for arranging characters for alphabetical processing or dictionary-based analysis.

Output

$ javac SortStringsAlphabetically.java
$ java SortStringsAlphabetically
Enter a string to sort: oodlescoop
Sorted String is cdeloooops