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  

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

}}}

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.

    Like

Leave a comment