Write a java program to sort array or list of string in alphabetical order.

Sometimes we are asked to sort strings or names array into dictionary or lexicographical order, that also means Alphabetical order so don’t get confused.


So we need to compare two strings alphabetically i.e character by character. For that, we will use the String class compareTo() method.

compareTo() in Java

compareTo() is a String class method which returns the lexicographical difference between two Strings(i.e compares two strings lexicographically). compareTo() method can be accessed by the instance of String class.


So if the compareTo() returns +ve number then first string (i.e str1) should come after second string (i.e str2) in the dictionary, else vice-versa.

Since the compareTo() method treats the upper case alphabet (e.g A) and lower case (e.g a) alphabet differently, so we first need to transform the strings into the lower case using String class toLowerCase() method before comparing them.

We will use Bubble Sort algorithm in this program.

Sort String Array in Java using compareTo()


Sort String List in Java

Though we can use the same mechanism i.e using compareTo() method, as done in the above program to sort a String list but there is another simple way to sort List in Java by using Collections.sort() available in java.util package.


If you have any doubts or suggestion then comment below.

Leave a Reply