Java Reference
In-Depth Information
To determine the relative ordering of two strings, use the
compareTo
method
of the
String
class. The
compareTo
method is more versatile than the
equals
method. Instead of returning a
boolean
value, the
compareTo
method returns
an integer. The return value is negative if the
String
object through which the
method is invoked precedes (is less than) the string that is passed in as a param-
eter. The return value is zero if the two strings contain the same characters.
The return value is positive if the
String
object through which the method is
invoked follows (is greater than) the string that is passed in as a parameter. For
example:
int
result = name1.compareTo(name2);
if
(result < 0)
System.out.println (name1 + " comes before " + name2);
else
if
(result == 0)
System.out.println ("The names are equal.");
else
System.out.println (name1 + " follows " + name2);
Keep in mind that comparing characters and strings is based on the Unicode
character set (see Appendix C). This is called a
lexicographic ordering
. If all alpha-
betic characters are in the same case (upper or lower), the lexicographic ordering
will be alphabetic ordering as well. However, when comparing two strings, such
as
"able"
and
"Baker"
, the
compareTo
method will conclude that
"Baker"
comes
first because all of the uppercase letters come before all of the lowercase letters
in the Unicode character set. A string that is the prefix of another, longer string
is considered to precede the longer string. For example, when comparing the
two strings
"horse"
and
"horsefly"
, the
compareTo
method will conclude that
"horse"
comes first.
SELF-REVIEW QUESTIONS
(see answers in Appendix N)
SR 5.13
Why must we be careful when comparing floating point values for
equality?
SR 5.14
How do we compare strings for equality?
SR 5.15
Write an
equals
method for the
Die
class of Section 4.2. The method
should return
true
if the
Die
object it is invoked on has the same
facevalue
as the
Die
object passed as a parameter, otherwise it should
return
false
.
SR 5.16
Assume the
String
variables
s1
and
s2
have been initialized. Write an
expression that prints out the two strings on separate lines in lexico-
graphic order.
Search WWH ::
Custom Search