Java Reference
In-Depth Information
Now consider the following object declarations:
String name1 = "Ada, Countess of Lovelace";
String name2 = "Grace Murray Hopper";
Initially, the references name1 and name2 refer to two different String objects:
name1
"Ada, Countess of Lovelace"
name2
"Grace Murray Hopper"
Now suppose the following assignment statement is executed, copying the value
in name1 into name2 :
name2 = name1;
This assignment works the same as the integer assignment—a copy of the value
of name1 is stored in name2 . But remember, object variables hold the address of
an object, and it is the address that gets copied. Originally, the two references
referred to different objects. After the assignment, both name1 and name2 contain
the same address and therefore refer to the same object:
name1
"Ada, Countess of Lovelace"
name2
The name1 and name2 reference variables are now aliases of each
other because they are two names that refer to the same object. All
references to the object originally referenced by name2 are now gone;
that object cannot be used again in the program.
One important implication of aliases is that when we use one reference to change
an object, it is also changed for the other reference because there is really only one
object. Aliases can produce undesirable effects unless they are managed carefully.
All interaction with an object occurs through a reference variable, so we can
use an object only if we have a reference to it. When all references to an object
are lost (perhaps by reassignment), that object can no longer contribute to the
program. The program can no longer invoke its methods or use its variables. At
this point the object is called
KEY CONCEPT
Multiple reference variables can refer
to the same object.
garbage because it serves no useful purpose.
Java performs automatic garbage collection . When the last reference to an
object is lost, the object becomes a candidate for garbage collection. Occasionally,
behind the scenes, the Java environment executes a method that “collects” all the
 
 
Search WWH ::




Custom Search