All About Basic


Home | Need Help? | Archives


Java: How to sort string in alphabetical order.

December 18, 2010 3:11 am

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]);

}}}

Posted by allaboutbasic

Categories: Java Basic Problems

Tags:

One Response to “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.

    Like

    By hanif on September 20, 2011 at 4:10 pm

Leave a Reply



Mobile Site | Full Site


Get a free blog at WordPress.com Theme: WordPress Mobile Edition by Alex King.