Java Reference
In-Depth Information
You may wonder why I didn't use the more familiar equality operator (==) to
evaluate
localText
. This is because
String
s are objects and not intrinsic data types.
Therefore, the equality operation would compare the object reference variables and
not the text contained in those objects.
if (localText == "Some other text") {
...
}
This is a valid statement and looks natural, but it is really one you will hardly
ever use. It can be read the following way: “Compare the object reference variable
localText
for equality to the (implicit) object reference variable that contains
'Some other text.' Return true if they are exactly equal.”
Since object reference variables contain the memory location of the object,
this statement will be true only if both variables point to exactly the same location
in memory! This will rarely be true, so the preceding statement will almost always
fail. It is clearly not the way to test
String
variables or any other types of objects for
equal text values.
String
s have a number of special characteristics assigned to them by Java. One is the
fact that they are considered
immutable
, meaning that they cannot change.
“Wait a minute!” you may be saying. “We saw some examples that changed the
value of
String
variables.”
Actually, there were no such examples. In reality, new
String
s are created when
required, and the
String
variable was changed to point to the new object. Consider
the original
String
definition statement:
String localText = "Some text";
A subsequent statement can cause
localText
to point to another
String
:
localText = "Some other text";
Follow what really happens when this statement is executed:
1. A new
String
object containing the text “Some other text” is created when
required by the runtime.
2. The
String
reference variable
localText
is changed to point to this object
instead of the original object.
3. The original
String
object (“Some text”) is marked as unused and may
eventually be deleted.