Java Reference
In-Depth Information
Do not use the
==
operator to compare strings. The expression
if (string1 == string2) //
Not useful
has an unrelated meaning. It tests whether the two string variables refer to the
identical string object. You can have strings with identical contents stored in
different objects, so this test never makes sense in actual programming; see
Common Error 5.1
.
In Java, letter case matters. For example,
ÐHarryÑ
and ȒHARRYȓ are not the
same string. To ignore the letter case, use the
equal sIgnoreCase
method:
if (string1.equalsIgnoreCase(string2)) . . .
If two strings are not identical to each other, you still may want to know the
relationship between them. The
compareTo
method compares strings in
dictionary order. If
The
compareTo
method compares strings in dictionary order.
string1.compareTo (string2) < 0
189
190
Figure 3
Lexicographic Comparison
then the string
string1
comes before the string
string2
in the dictionary. For
example, this is the case if
string1
is
ÐHarryÑ
, and
string2
is
ÐHelloÑ
. If
string1.compareTo(string2) > 0
then
string1
comes after
string2
in dictionary order. Finally, if
string1. compareTo (string2) == 0