Java Basic Problems

Java: How to sort string in alphabetical order.

In my last post I have tried to share about How to convert integer variable to object type in java.Today I will share with you about how to sort string in an array alphabetically.

Here compareTo() function is used to sort string in an alphabetical order in java.

According to compareTo() function  a string is less than another if it comes before the other in   dictionary order and a string is greater than another if it comes after the other in dictionary  


If you want to ignore case differences when comparing two strings, use compareToIgnoreCase( ),

 String sorting in alphabetical order in java

Code Example:

class StringOrder


 static String name[]={“Chittagong”,”Dhaka”,”Rangpur”,”Sonargaon”,”Bangladesh”};

public static void main(String args[])


int size= name.length;

String temp=null;


for(int i=0;i<size;i++)


for(int j=i+1;j<size;j++)




//System.out.println(“name[j]:”+name[j]+”compareTo(name[i]):< 0:”+name[i]);





for(int i=0;i<size;i++)




1 thought on “Java: How to sort string in alphabetical order.”

  1. hai everything is ok……….,but can any tell ,the internal process of the compare function,..i mean that how does it compare a string with a integer.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s