Practical-35
Write a Java Program which will read a string and rewrite it in the alphabetical order eg.The word 'STRING' should be written a 'GINRST'.
Introduction
This Java program will take a string as an input, convert the string into a char array, and then reorder the characters according to their alphabetical order. The program will then create a new String object and return it with the characters arranged in alphabetical order. The program will be able to handle uppercase and lowercase letters and also white spaces between words.
Prerequisites include knowledge of the Java language, as well as familiarity with classes, variables, and methods.
Code
import java.util.Arrays;
public class AlphabeticalOrder {
public static String order(String word) {
char tempArray[] = word.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
public static void main(String args[]) {
String word = "STRING";
System.out.println("Input String: "+word);
System.out.println("Output String: "+order(word));
}
}
Output
Input String: STRING
Output String: GINRST
Explanation
The above Java code splits the input string into a char array, and then uses the Arrays.sort method to sort the char array in alphabetical order. The program then creates a new string object with the characters in the sorted array.