Comparing string object

3.5 Comparing string object

It is often necessary to compare strings to see if they are the same, or to see which comes first in alphabetical order. It would be nice if we could use the comparison operators, like == and >, but we can't. To compare Strings, we have to use the equals and compareTo methods.
Syntax for using method compareTo :
str1.compareTo(str2);
The method compareTo returns an integer value less than 0 if string str1 is less than string str2; 0 if string str1 is equal to string str2; an integer value greater than 0 if string str1 is greater than string str2
Syntax for using method equals :
st1.equals(str2)
The method equals determine whether two String objects contain the same value. The method equals returns the value true or false.
Following example illustrate this:

String name1 = "Alan Turing";
String name2 = "Ada Lovelace";

if (name1.equals(name2))
{
   System.out.println("The names are the same.");
}
else
{
   System.out.println("The names are not same.");
}


int flag = name1.compareTo(name2);

if (flag == 0)
{
   System.out.println("The names are the same.");
}
else if (flag < 0)
{
   System.out.println("name1 comes before name2.");
}
else
{
   System.out.println("name2 comes before name1.");
}

No comments:

Post a Comment

Pages