4.2 Conditions and Logical Expressions | 159
Table 4.1 Java Comparison and Case-Conversion Methods
Method Name Argument Type Returns Operation Performed
equals
equalsIgnoreCase
compareTo
toLowerCase
toUpperCase
String
String
String
boolean
boolean
int
String
String
Tests for equality of string
contents.
Returns trueif the strings are
equal, ignoring the case of the
letters. Returns falseif they
are unequal.
Returns 0 if equal, a positive
integer if this string comes
after the string in the
argument, and a negative in-
teger if it comes before the
argument string.
Returns a new identical string
except that the characters are
all lowercase.
Returns a new identical string
except that the characters are
all uppercase.
percase, respectively. The three most useful comparison methods are summarized in Table
4.1, along with toLowerCaseand toUpperCase.
Many of Java’s classes support a method calledcompareTo. As we will see in later chapters,
this common use ofcompareToenables the same piece of code to compare objects of differ-
ent classes. With strings, we often combine the use ofcompareTowith eithertoLowerCaseor
toUpperCase, as we show below. Note thatequalsandequalsIgnoreCasetest only for equality.
We must use thecompareTomethod to test for relationships such as “greater than” or “less than.”
Let’s look at some examples. If lastNameis a Stringvariable, we can write
lastName.equals("Olson") // Tests whether lastName equals "Olson"
Because every Stringliteral is also a Stringobject, Java lets us append the method call to a
literal, if we so choose.
"Olson".equals(lastName) // Tests whether lastName equals "Olson"
As another example, we might write
lastName.compareTo("Olson") > 0 // Tests if lastName comes after "Olson"