At what point is the Bar object, created on line 6, eligible for garbage collection?
class Bar { }
class Test
{
Bar doBar()
{
Bar b = new Bar(); /* Line 6 */
return b; /* Line 7 */
}
public static void main (String args[])
{
Test t = new Test(); /* Line 11 */
Bar newBar = t.doBar(); /* Line 12 */
System.out.println("newBar");
newBar = new Bar(); /* Line 14 */
System.out.println("finishing"); /* Line 15 */
}
}
- A after line 12
- B after line 14
- C after line 7, when doBar() completes
- D after line 15, when main() completes
0 voters
Answer
Option B
Explanation: [spoiler]Option B is correct. All references to the Bar object created on line 6 are destroyed when a new reference to a new Bar object is assigned to the variable newBar on line 14. Therefore the Bar object, created on line 6, is eligible for garbage collection after line 14.
Option A is wrong. This actually protects the object from garbage collection.
Option C is wrong. Because the reference in the doBar() method is returned on line 7 and is stored in newBar on line 12. This preserver the object created on line 6.
Option D is wrong. Not applicable because the object is eligible for garbage collection after line 14.[/spoiler]