Java Reference
In-Depth Information
LISTING 3.5
Continued
11: str2 = new String(str1);
12:
13: System.out.println(“String1: “ + str1);
14: System.out.println(“String2: “ + str2);
15: System.out.println(“Same object? “ + (str1 == str2));
16: System.out.println(“Same value? “ + str1.equals(str2));
17: }
18: }
This program's output is as follows:
String1: Free the bound periodicals.
String2: Free the bound periodicals.
Same object? true
String1: Free the bound periodicals.
String2: Free the bound periodicals.
Same object? false
Same value? true
3
The first part of this program declares two variables (
str1
and
str2
), assigns the literal
“Free the bound periodicals.” to
str1
, and then assigns that value to
str2
(lines 3-5). As
you learned earlier,
str1
and
str2
now point to the same object, and the equality test at
line 9 proves that.
In the second part of this program, you create a new
String
object with the same value
as
str1
and assign
str2
to that new
String
object. Now you have two different string
objects in
str1
and
str2
, both with the same value. Testing them to see whether they're
the same object by using the
==
operator (line 15) returns the expected answer:
false
—
they are not the same object in memory. Testing them using the
equals()
method in line
16 also returns the expected answer:
true
—they have the same values.
NOTE
Why can't you just use another literal when you change
str2
,
instead of using
new
? String literals are optimized in Java; if you
create a string using a literal and then use another literal with the
same characters, Java knows enough to give you the first
String
object back. Both strings are the same objects; you have to go out
of your way to create two separate objects.