











Java program to sort a String in alphabetical order
Sort a string in alphabetical order
In this java program, we’re to going to sort a String in alphabetical order. First, we will take String input from the user and store it in the variable “s” (in this case). After that we will convert String to character array using tocharArray() method then we’re using sort() method present in Arrays class to sort the string.
for example, if we take a string prepinsta then sorted string is ‘aeinpprst’ , if we take coding then sorted string is ‘cdgino’.


Algorithm
- Take a String input from user and store it in the variable called “s” (in this case)
- After that convert String to character array using tocharArray() method
- Use Arrays class sort method to sort() the character array
- At last print sorted array System.out.println(c)
Code in Java
import java.util.Arrays; import java.util.Scanner; public class SortAStringAlphabetically { public static void main(String[] args){ Scanner sc = new Scanner(System.in); System.out.print("Enter String :"); String s = sc.nextLine(); char[] c = s.toCharArray(); Arrays.sort(c); System.out.println(c); } } This code is contributed by Shubham Nigam (Prepinsta Placement Cell Student)
Output
Enter String :prepinsta
aeinpprst
Thank you prepinsta for publishing my code…