Thursday 9 February 2017

Java String compareTo() method



compareTo() method:

You're comparing the strings lexicographically when you use compareTo(). This returns numbers that compare the strings based on the fact that each character in a string is actually an ASCII value (a number) to the computer. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string.

Return Value :

The value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.
Consider the following example:

CompareToTest.java


 public class CompareToTest
 {
  public static void main(String args[])
  {
   String str1 = "java";
   String str2 = new String("java");
   String str3 = new String("java is fun");

   int result = str1.compareTo( str2 );
   System.out.println(result);

   result = str2.compareTo( str3 );
   System.out.println(result);
  }
 }

The output generated by above program is:
0
-7

If you want to ignore case while comparing string, use compareToIgnoreCase(). The general form is:

Int compareToIgnoreCase(String str);

This method return the same result as compareTo(), except that case difference are ignored.

 Next Topic Shahbaz

0 comments:

Post a Comment

Powered by Blogger.

Stats