Java Reference
In-Depth Information
PITFALL: (continued)
Notice that it is perfectly legal to use a quoted string with a
String
method, as in
the preceding use of
equalsIgnoreCase
. A quoted string is an object of type
String
and has all the methods that any other object of type
String
has.
For the kinds of applications we are looking at in this chapter, you could also use
==
to test for equality of objects of type
String
, and it would deliver the correct answer.
However, there are situations in which
==
does not correctly test strings for equality, so
you should get in the habit of using equals rather than
==
to test strings.
■
Lexicographic and Alphabetical Order
The method
compareTo
tests two strings to determine their lexicographic order.
Lexicographic ordering
is similar to alphabetic ordering and is sometimes, but not
always, the same as alphabetic ordering. The easiest way to think about lexicographic
ordering is to think of it as being the same as alphabetic ordering
but with the
alphabet ordered differently
. Specifically, in lexicographic ordering, the letters and other
characters are ordered as in the ASCII ordering , which is shown in Appendix 3 .
If
s1
and
s2
are two variables of type
String
that have been given
String
values, then
lexicographic
ordering
compareTo
s1.compareTo(s2)
returns a negative number if
s1
comes before
s2
in lexicographic ordering, returns zero if
the two strings are equal, and returns a positive number if
s2
comes before
s1
. Thus,
s1.compareTo(s2) < 0
returns true if
s1
comes before
s2
in lexicographic order and returns false otherwise.
For example, the following will produce correct output:
if
(s1.compareTo(s2) < 0)
System.out.println(
s1 + " precedes " + s2 + " in lexicographic ordering");
else if
(s1.compareTo(s2) < 0)
System.out.println(
s1 + " follows " + s2 + " in lexicographic ordering");
else
//s1.compareTo(s2) == 0
System.out.println(s1 + " equals " + s2);
If you look at the ordering of characters in Appendix 3 , you will see that
all
uppercase letters come before
all
lowercase letters. For example,
'Z'
comes before
'a'
in lexicographic order. So when comparing two strings consisting of a mix of lower- and
uppercase letters, lexicographic and alphabetic ordering are not the same. However, as