Java Reference
In-Depth Information
The special case of assignment and equality as applied to object reference vari-
ables warrants attention. An object reference variable is just like any other variable
in many ways. But remember that it contains a reference to the object and does not
contain the object's values. Therefore, although two different object reference vari-
ables can point to different objects with equal values, they are not the
same
object.
The only way that two object reference variables can be equal is if they point to the
same object.
Some examples may help clarify this. Recall that the
String
data type is not re-
ally an intrinsic type, but rather, is a class. Therefore,
String
variable names are ac-
tually object reference variables. Consider this example:
String s1 = new String ("Some text");
Often, the following syntax is used instead of the previous declaration:
String s1 = "Some text";
Suppose the program also includes this statement:
String s2 = "Some other text";
Clearly,
s1
and
s2
are not equivalent, so this test fails, as you would expect.
if (s1 == s2) {
... // This code would not execute
}
In addition, the following test will also fail, since
s1
and
s2
do not contain
equivalent text:
if (s1.equals (s2)) {
... // This code will not execute
}
Now, suppose you have two
String
s that contain the same text.
String s1 = new String ("Some text");
String s2 = new String ("Some text");