English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Arrays

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collections

Java Set Collections

Java Input/Output (I/O)

Java Reader/Writer

Other Java Topics

Java program sorts elements in alphabetical order

Comprehensive Java Examples

In this program, you will learn to use for loops and if using Java, sort elements by alphabetical order.

Example: A program to sort strings in alphabetical order

public class Sort {
    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) {
                    // words[i] and words[j] swap 
                    String temp = words[i];
                    words[i] = words[j];
                    words[j] = temp;
                }
            }
        }
        System.out.println("In alphabetical order:");
        for(int i = 0; i < 4; i++) {
            System.out.println(words[i]);
        }
    }
}

When running the program, the output is:

In alphabetical order:
C
Java
Python
Ruby

In the above program, the word to be sorted5The list of words is stored in the variable word.

Then, we traverse each word (words [i]) and compare it with all the words after it in the array (words [j]). This is done by using the string's compareTo() method.

If the return value of compareTo() is greater than 0, an exchange must be made on the position, that is, word [i] after word [j]. Therefore, in each iteration, the word [i] contains the earliest word

Execution Steps
IterationInitial Wordijwords[]
1{ "Ruby", "C", "Python", "Java" }01{ "C", "Ruby", "Python", "Java" }
2{ "C", "Ruby", "Python", "Java" }02{ "C", "Ruby", "Python", "Java" }
3{ "C", "Ruby", "Python", "Java" }03{ "C", "Ruby", "Python", "Java" }
4{ "C", "Ruby", "Python", "Java" }12{ "C", "Python", "Ruby", "Java" }
5{ "C", "Python", "Ruby", "Java" }13{ "C", "Java", "Ruby", "Python" }
Final{ "C", "Java", "Ruby", "Python" }23{ "C", "Java", "Python", "Ruby" }

 

Comprehensive Java Examples