Java Reference
In-Depth Information
This is done rather than creating a new object and assigning the new object's memory address to name2 (as in step 1).
In other words, step 4 saves memory space because only one object is created (as in step 2) instead of two objects
(as in step 1).
Now that we have opened up this can of worms, we need to explain another String “feature” regarding changing
values. If you change the value of a String , the JVM creates a new String object and changes the variable to point to
the new object. The old String object still resides in memory: however, no String variable points to it.
5.
Comment out the current main method statements, add the following, and run
the application:
String name1 = new String("Joe");
String name2 = name1;
System. out .println(name1 == name2);
name1 = "Mary";
System. out .println(name2 + " " + name1);
The results will be as follows:
true
Joe Mary
The fourth statement ( name1 = "Mary";) creates a new object (just as if you had specified name1 = new
String("Mary"); ) and the old object, with the value “Joe”, is still in memory. We know this because name2 is still
pointing to it. If we added a statement to change name2 to “Sam”, a new object would be created, name2 would be set
to point to the new object, and the original object with “Joe” would be in memory with no variable pointing to it.
Intuitively most people think that strings should work the same as primitives (i.e., a new value simply replaces
the old value in the original memory location), as seen in Figure 6-12 :
Figure 6-12.
The new value 99 replaces the old value 1.
However, when a new value is assigned to a string, a new object is created and the old object stays in main
memory. The memory allocation looks like Figure 6-13 .
Search WWH ::




Custom Search