The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. |
Home Strings and Things Strings Are Incomparable | ||
Search the VIAS Library | Index | ||
Strings Are Incomparable
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. In order to compare Strings, we have to use the equals and compareTo methods. For example: String name1 = "Alan Turing";String name2 = "Ada Lovelace"; if (name1.equals (name2)) { System.out.println ("The names are the 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 if (flag > 0) { System.out.println ("name2 comes before name1."); } The syntax here is a little weird. To compare two things, you have to invoke a method on one of them and pass the other as an argument. The return value from equals is straightforward enough; true if the strings contain the same characters, and false otherwise. The return value from compareTo is a little odd. It is the difference between the first characters in the strings that differ. If the strings are equal, it is 0. If the first string (the one on which the method is invoked) comes first in the alphabet, the difference is negative. Otherwise, the difference is positive. In this case the return value is positive 8, because the second letter of "Ada" comes before the second letter of "Alan" by 8 letters. Using compareTo is often tricky, and I never remember which way is which without looking it up, but the good news is that the interface is pretty standard for comparing many types of objects, so once you get it you are all set. Just for completeness, I should admit that it is legal, but very seldom correct, to use the == operator with Strings. But what that means will not make sense until later, so for now, don't do it.
|
||
Home Strings and Things Strings Are Incomparable |