1Z0-829 · Question #44
Given: public class App{ String name; public App(String name){ this.name = name; } public static void main(String args[]) { App t1 = new App("t1"); App t2 = new App("t2"); t1 = t2; t1 = null…
The correct answer is B. Both the objects previously referenced by t1 are eligible for garbage collection. There is an error in the provided answer key. The correct answer is actually D, not B. Here is the explanation: Why D is correct: Tracing the references step by step: `` App t1 = new App("t1"); // t1 → Object_A App t2 = new App("t2"); // t2 → Object_B t1 = t2; // t1 → Object_B…
Question
Options
- AOnly the object referenced by t2 is eligible for garbage collection.
- BBoth the objects previously referenced by t1 are eligible for garbage collection.
- CNone of the objects are eligible for garbage collection.
- DOnly one of the objects previously referenced by t1 is eligible for garbage collection.
How the community answered
(33 responses)- A3% (1)
- B82% (27)
- C12% (4)
- D3% (1)
Explanation
There is an error in the provided answer key. The correct answer is actually D, not B. Here is the explanation:
Why D is correct:
Tracing the references step by step:
App t1 = new App("t1"); // t1 → Object_A
App t2 = new App("t2"); // t2 → Object_B
t1 = t2; // t1 → Object_B, t2 → Object_B (Object_A loses all references)
t1 = null; // t1 → null, t2 → Object_B
When System.out.println("GC") executes, t2 still holds a live reference to Object_B, so Object_B is not eligible for GC. Only Object_A (the original new App("t1")) is eligible - it lost its last reference at t1 = t2. Since t1 previously referenced both objects but only one is now unreachable, D is correct.
Why the other choices are wrong:
- A - Object_B (referenced by
t2) is the one not eligible; Object_A is eligible. This is backwards. - B - Incorrect because
t2still holds a live reference to Object_B, keeping it alive. - C - Incorrect because Object_A has no remaining references and is eligible for GC.
Memory tip: Think of reference variables as ropes tied to objects. An object gets garbage collected only when all ropes are cut. Setting t1 = null only cuts t1's rope; t2's rope to Object_B remains, so Object_B survives.
Topics
Community Discussion
No community discussion yet for this question.