Strings

Java Program to Sort Strings in Alphabetical Order

A Java program to sort strings in dictionary order.

Problem Description

Write a Java program to sort a list of strings in alphabetical (dictionary) order.

Code

SortStrings.java
public class SortStrings {
    public static void main(String[] args) {
        String[] words = { "Ruby", "C", "Python", "Java" };

        for(int i = 0; i < 3; ++i) {
            for (int j = i + 1; j < 4; ++j) {
                if (words[i].compareTo(words[j]) > 0) {
                    // swap words[i] and words[j]
                    String temp = words[i];
                    words[i] = words[j];
                    words[j] = temp;
                }
            }
        }

        System.out.println("In lexicographical order:");
        for(int i = 0; i < 4; i++) {
            System.out.println(words[i]);
        }
    }
}

Output

In lexicographical order:
C
Java
Python
Ruby

Explanation

  1. compareTo(): Compares two strings lexicographically.
  2. Bubble Sort: Used here to sort the array of strings.