Java Reference
In-Depth Information
"HTML"
and assigns its reference to
s
. The first
String
object still exists after the assign-
ment, but it can no longer be accessed, because variable
s
now points to the new object, as
shown in Figure 9.1.
After executing
String s = "Java";
After executing
s = "HTML";
This string object is
now unreferenced
s
: String
: String
s
String object for
"Java"
String object for
"Java"
Contents cannot be changed
: String
String object for
"HTML"
F
IGURE
9.1
Strings are immutable; once created, their contents cannot be changed.
Because strings are immutable and are ubiquitous in programming, the JVM uses a
unique instance for string literals with the same character sequence in order to improve effi-
ciency and save memory. Such an instance is called an
interned string
. For example, the fol-
lowing statements:
interned string
String s1 =
"Welcome to Java"
;
s1
: String
s3
String s2 =
new
String(
"Welcome to Java"
);
Interned string object for
"Welcome to Java"
String s3 =
"Welcome to Java"
;
s2
: String
System.out.println(
"s1 == s2 is "
+ (s1 == s2));
System.out.println(
"s1 == s3 is "
+ (s1 == s3));
A string object for
"Welcome to Java"
display
s1 == s2 is false
s1 == s3 is true
In the preceding statements,
s1
and
s3
refer to the same interned string—
"
Welcome to
Java
"
—so
s1 == s3
is
true
. However,
s1 == s2
is
false
, because
s1
and
s2
are two
different string objects, even though they have the same contents.
9.2.3 String Comparisons
The
String
class provides the methods for comparing strings, as shown in Figure 9.2.
How do you compare the contents of two strings? You might attempt to use the
==
opera-
tor, as follows:
==
if
(string1 == string2)
System.out.println(
"string1 and string2 are the same object"
);
els
System.out.println(
"string1 and string2 are different objects"
);
However, the
==
operator checks only whether
string1
and
string2
refer to the same object;
it does not tell you whether they have the same contents. Therefore, you cannot use the
==
oper-
ator to find out whether two string variables have the same contents. Instead, you should use the
equals
method. The following code, for instance, can be used to compare two strings:
if
(string1.equals(string2))
System.out.println(
"string1 and string2 have the same contents"
);
els
System.out.println(
"string1 and string2 are not equal"
);
string1.equals(string2)