How to Sort Strings in Java
Here you will get solution, that how to sort strings in java programming. In this program we will take n input from user, then process to sort strings in ascending order, and lastly print the result.
Program code: How to Sort Strings in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | import java.util.Scanner; public class SortStrings{ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); //input number of strings from user System.out.print("How many strings you want to sort : "); int num = scanner.nextInt(); scanner.nextLine(); String[] strArray = new String[num]; //getting input from user for (int i = 0; i < num; i++) { System.out.print("Enter " + (i + 1)+ " String " + ": "); String inStr = scanner.nextLine(); strArray[i] = inStr; } //Sorting strings for (int i = 0; i < num - 1; i++) { for (int j = 0; j < num - i - 1; j++) { if (strArray[j].compareTo(strArray[j + 1]) > 0) { // Swap the strings String temp = strArray[j]; strArray[j] = strArray[j + 1]; strArray[j + 1] = temp; } } } // print sorted strings System.out.println("Strings Sorted in Ascending Order : "); for (int i = 0; i <= num - 1; i++) { System.out.println(strArray[i]); } scanner.close(); } } |
Output
C:\CodeRevise\java>javac SortStrings.java
C:\CodeRevise\java>java SortStrings
How many strings you want to sort : 5
Enter 1 String : Rocky
Enter 2 String : Amit
Enter 3 String : Rajan
Enter 4 String : Rohan
Enter 5 String : Navya
Strings Sorted in Ascending Order :
Amit
Navya
Rajan
Rocky
Rohan
Check out our other Java Programming Examples