Java Reference
In-Depth Information
PITFALL:
(continued)
The method
equalsIgnoreCase
behaves similarly to
equals
, except that with
equalsIgnoreCase
, the upper- and lowercase versions of the same letter are considered
the same. For example,
"Hello"
and
"hello"
are not equal because their first characters,
'H'
and
'h'
, are different characters. But they would be considered equal by the method
equalsIgnoreCase
. For example, the following will output
Equal
ignoring case.
:
if
("Hello".equalsIgnoreCase("hello"))
System.out.println("Equal ignoring case.");
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.
Lexi-
cographic 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);