posted 11 years ago
In the following code, after which statement (earliest), will the object originally held in 's' be eligible for garbage collection ?
Select 1 Option
a. It will not be Garbage Collected till the end of the program.
b. Line 5
c. Line 6
d. Line 7
e. Line 10
-------
Answer: c
Explanation:
Since there is only one reference to Student object, as soon as it is set to null, the object held by the reference is eligible for GC, here it is done at line 6.
Note that although an object is created at line 7 with the same parameters, it is a different object and it will be eligible for GC after line 10.
________________________________________________________
The question asks, after which statement (earliest), will the object originally held in 's' be eligible for garbage collection ?
The way I should interpret this statement is ,
as soon as the reference variable 's' is set to null, it becomes eligible for garbage collection.
Sequence of Events:
1) Reference variable 's' is set to null on line 6
2) Reference variable 's' (which created the original object on line 3) is now eligible for garbage collection
3) On line 7 the same reference variable 's' is used again to create a new object.
(This is a new object and the previous object, which has had its reference variable set to null is now eligible for garbage collection,
since we do not know when the JVM is going to collect the object pointed to by the reference variable 's' .)
Please confirm.