program to sort the string in alphabetical order in java

Simple java program to sort and  print the names in alphabetical order using compareTO(). To arrange the given strings in alphabetical order, first we need to compare each consecutive string and swap them according to the order. In this example, built-in function compareTo()  is used to compare two string.
Example of compareTo:

                    str1.compareTo(str2)               

This will return integer value as result. Value returned will be one of the below three.
               Return      0  -> if the two strings are equal.
              Return  >=1  -> if str1 comes after str2 in alphabetical order
              Return <=1   -> if str1 comes before str2 in alphabetical order.

Code:
 

string[] names={"pradeesh","Techietet","Apple"};

            int i=0; 
               while(i<2 && i>=0){

                if(names[i].CompareTo (names[i+1]) >= 1 ) {
                    string temp;
                    temp = names[i];
                    names[i]=names[i+1];
                    names[i+1]=temp;
                    i--;
                }
                else { i++;}
            }

            // to display
            for (i=0; i<=2; i++) {
                System.out.println (names [i]);
            }

 

Usually compareTo used to find whether the two strings are equivalent or greater or lower in alphabetical order.
Output:

Apple

pradeesh

Techietet
 

 

Explanation:

if (names[i].CompareTo (names[i+1]) >= 1)
Check whether the names[i] comes after names[i+1] in alphabetical order, if its true.
Swap the values.
When i=0

  •  String "pradeesh" and "Techietet" are compared, it will not satisfy the if condition.
  • so, the values are not been swapped and variable i will be incremented to point next string in the array.

when i=1

  •  String "Techietet" and "Apple" are compared, it will satisfy the if condition.
  •  So, the values are been swapped and variable i will be decremented to point previous string in the array
  •  Now the value in array is: names[]={"pradeesh","Apple","Techietet"}

 In the previous step i is decremented so, "pradeesh","Apple" will be compared and sorted accordingly.

compareTo(object)

Even object can be compared, which Compares this instance with a specified Object and result return whether this instance precedes, follows, or appears in the same position in the sort order as the specified Object.