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( ),
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]);
}}}
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.
LikeLike