Java Reference
In-Depth Information
then
string1
and
string2
are equal.
Actually, the Ȓdictionaryȓ ordering used by Java is slightly different from that of a
normal dictionary. Java is case sensitive and sorts characters by putting numbers
first, then uppercase characters, then lowercase characters. For example, 1 comes
before
B
, which comes before
a
. The space character comes before all other
characters.
Let us investigate the comparison process closely. When Java compares two
strings, corresponding letters are compared until one of the strings ends or the first
difference is encountered. If one of the strings ends, the longer string is considered
the later one. If a character mismatch is found, the characters are compared to
determine which string comes later in the dictionary sequence. This process is
called lexicographic comparison. For example, let's compare
ÐcarÑ
with
ÐcargoÑ
. The first three letters match, and we reach the end of the first string.
Therefore
ÐcarÑ
comes before
ÐcargoÑ
in the lexicographic ordering. Now
compare
ÐcathodeÑ
with
ÐcargoÑ
. The first two letters match. In the third
character position,
t
comes after
r
, so the string
ÐcathodeÑ
comes after
ÐcargoÑ
in lexicographic ordering. (See
Figure 3
.)
C
OMMON
E
RROR
5.1: Using
==
to Compare Strings
It is an extremely common error in Java to write
==
when
equals
is intended.
This is particularly true for strings. If you write
if (nickname == "Rob")
then the test succeeds only if the variable
nickname
refers to the exact same
string object as the string constant
ÐRobÑ
. For efficiency, Java makes only one
string object for every string constant. Therefore, the following test will pass:
String nickname = "Rob";
. . .
if (nickname == "Rob") //
Test is true
190
191
However, if the string with the letters
R o b
has been assembled in some other
way, then the test will fail:
String name = "Robert";