Java Reference
In-Depth Information
if (s1 == s2) {
// This code will not execute
// even though the text contained in these
// two Strings are equal. s1 and s2 will
// point to different String objects
}
Yet the following test always succeeds since the
equals()
method in the
String
class compares the value of the
String
object with the passed
String:
if (s1.equals (s2)) {
... // This code will execute
}
What is the bottom line? Always use the
equals()
or
compareTo()
methods
when you want to compare two
String
s. Never assume that the
String
reference
variables will compare appropriately, based on the text values in the
String
.
Get ready for the real weirdness. Object reference variables are variables and,
therefore, can be assigned values. Normally, this happened only with the
new
key-
word, as in the following:
String s1 = new String ("Some text");
String s2 = new String ("Some other text");
But it is perfectly legal to set object reference
s2
equal to
s1
:
s2 = s1;
Now, both
s2
and
s1
point to the same object. (As a matter of fact, the object
formerly pointed to by
s2
could be unreferenced and will likely be garbage collected
or deleted by the system at some point.) This time, the equality test, when applied
to the values of the
String
s, will succeed even though the initial object pointed to
by
s2
was different from
s1
:
if (s1.equals (s2)) {
... // This code would execute
}
The same is true of this test, which compares the object references:
if (s1 == s2) {