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  

order.

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;

System.out.println(“\n”);

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

{

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

{

if(name[j].compareTo(name[i])<0)

{

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

temp=name[i];

name[i]=name[j];

name[j]=temp;

}}}

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

{

System.out.println(name[i]);

}}}

About these ads

One Response to Java: How to sort string in alphabetical order.

  1. hanif says:

    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:

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 303 other followers

%d bloggers like this: