Sunday, May 6, 2007

Comparing Strings

As mentioned in the previous post, relational operators are meant for comparing variables declared in the primitive data types, and not strings. Since strings are objects of the String class, we need to use methods to perform the comparison.

We introduced 3 methods for comparing strings.
  • compareTo() - This method compares 2 strings and returns an integer value. If the 2 strings are exactly the same (including the case), a 0 will be returned. Else, the method will return the difference between the 2 strings. Using the return value, we can use it to help us sort strings. Refer to Lab 3 for an example, which I will also elaborate in class.
  • equals() - This method also compares 2 strings but returns only the boolean values TRUE (when the strings are exactly the same) or FALSE (when the strings are not the same).
  • equalsIgnoreCase() - This method does the same thing as equals() but ignores the case.
We will be using these methods in Lab 3 and I hope it becomes clearer to you how the method works, when you get to use them in real programs.

As usual, leave comments if you have questions.

No comments: