compareTo Example in Java:
Often we need to know which strings are identical for sorting purpose to do this java has a method compareTo() this method compare two strings and returned its result as shown belowless than zero = string is less than string
greatet than zero = string is greater than string
Zero = The string are equal
CODING:
class stringsorting{
public static void main(String args[])
{
String arr[] = {"e","d","f","b","a","F"};
System.out.println("Before sorting:");
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
System.out.println("After sorting:");
for(int i=0;i<arr.length;i++)
{
for(int j=i+1;j<arr.length;j++)
{
if(arr[j].compareTo(arr[i])<0)
{
String t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
System.out.println(arr[i]);
}
}
}
No comments:
Post a Comment