Java Reference
In-Depth Information
To illustrate what is happening with garbage collection, consider the following code snippet.
class PersonManager {
public static void main(String args[]) {
Person p1 = new Person("Adam");
Person p2 = new Person("Robert");
p1 = p2;
...//Rest of program
}
}
A
Person
variable
p1
is declared and initialized to a newly created
Person
object with the name
Adam
. A second
Person
variable
p2
is declared and initialized to another newly created
Person
object with the name
Robert
. See Figure 7-4.
Person object
name = “Adam”
p1
Person object
name = “Robert”
p2
figure 7-4
In the next statement, the variable
p1
is reassigned to the reference object of
p2
. See Figure 7-5.
Person object
name = “Adam”
p1
Person object
name = “Robert”
p2
figure 7-5
The
Person
object with name
Adam
no longer has any references pointing to it. So it becomes eligible
for garbage collection. See Figure 7-6.
Person object
name = “Adam”
p1
Person object
name = “Robert”
p2
figure 7-6
Search WWH ::
Custom Search