Java Programs

Java Program for String Sorting Example

In this tutorial, we are going to write string  sorting example. In our daily development sorting is a very common requirement. To do so, Java API provides us a sort() method in Collections class.

But in this tutorial we are going to implement the logic to sort an array of strings. Here is the logical example for String Sorting using java.

Java Program Logic for String Sorting :

StringSortingDemo.java
public class StringSortingDemo {
    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        System.out.println("Enter array size:");
        int n = s.nextInt();
        String str[] = new String[n];
        System.out.println("Enter any " + n + " names");
        for (int i = 0; i < n; i++)
            str[i] = s.next();
        System.out.println("Before Sorting ");
        System.out.println("---------------");
        for (int i = 0; i < n; i++)
            System.out.println(str[i]);
        // Sorting
        for (int i = 0; i < n - 1; i++)
            for (int j = 0; j < n - i - 1; j++)
                if (str[j].compareToIgnoreCase(str[j + 1]) > 0) {
                    String temp = str[j];
                    str[j] = str[j + 1];
                    str[j + 1] = temp;
                }
        System.out.println("After Sorting");
        System.out.println("---------------");
        for (int i = 0; i < n; i++)
            System.out.println(str[i]);
    }
}

Output :

Enter array size:
5
Enter any 5 names
String
Sorting
Example
onlinetutorialspoint
java
Before Sorting
---------------
String
Sorting
Example
onlinetutorialspoint
java
After Sorting
---------------
Example
java
onlinetutorialspoint
Sorting
String

 

String Sorting using Java API :

import java.util.ArrayList;
import java.util.Collections;
public class String_Sorting{
    public static void main(String args[]) {
        ArrayList<String> namesList = new ArrayList<String>();
        namesList.add("We");
        namesList.add("Are");
        namesList.add("Doing");
        namesList.add("String");
        namesList.add("Sorting");
        System.out.println("Lets Check");
        Collections.sort(namesList);
        System.out.println("Sorted Strings : "+namesList);
    }
}

Output :

Lets Check
Sorted Strings : [Are, Doing, Sorting, String, We]

The above are the examples for sorting the Strings in Java. If you want to sort the user defined objects we can go with bean sorting in java example.

Happy Learning :)

Found a mistake or something out of date? Tell us →

Written by

chandrashekhar

Founder of onlinetutorialspoint.com. Enterprise architect with 15+ years in healthcare technology, designing and running systems on AWS and Azure. Writes about building real things with AI, local AI hardware and cloud certifications.

Keep reading

Ask a question or leave a comment