Sort Words Alphabetically in Java


Write a Java Program to sort words alphabetically.

Click Here to View the Solution!
public class AlphabeticallySort {
 public static void main(String[] args) {
 String[] words ={"New York","Washington","Houston","Toronto","London"};
     for(int i = 0; i < 3; ++i) {
       for (int j = i + 1; j < 4; ++j) {
         if (words[i].compareTo(words[j]) > 0) {
           // swapping words[i] with words[j]
           String temp = words[i];
           words[i] = words[j];
           words[j] = temp;
     System.out.println("In alphabetical order:");
     for(int i = 0; i < 4; i++) {
Click Here to View the Output!
In alphabetical order:
 New York
Click Here to View the Explanation!
  • In this program, an array variable words stores the set of five words which are to be ordered or sorted.
  • Next, every word in the array is iterated (words[i]) and is compared with all the other words (words[j]) occurring after its position in the array. The comparison between the words takes place with the help of a string method called compareTo().
  • compareTo() method will return a value greater than 0 if the order of the second word (words[j]) that is being compared is less than the order of the first word (words[i]). In this case, a swap occurs which changes the places of the words in the array and so, words[i] will contain the word with the lowest order after every loop