Java Programming - Garbage Collections - Discussion

Discussion Forum : Garbage Collections - General Questions (Q.No. 4)
4.
class Test 
{  
    private Demo d; 
    void start() 
    {  
        d = new Demo(); 
        this.takeDemo(d); /* Line 7 */
    } /* Line 8 */
    void takeDemo(Demo demo) 
    { 
        demo = null;  
        demo = new Demo(); 
    } 
}
When is the Demo object eligible for garbage collection?
After line 7
After line 8
After the start() method completes
When the instance running this code is made eligible for garbage collection.
Answer: Option
Explanation:

Option D is correct. By a process of elimination.

Option A is wrong. The variable d is a member of the Test class and is never directly set to null.

Option B is wrong. A copy of the variable d is set to null and not the actual variable d.

Option C is wrong. The variable d exists outside the start() method (it is a class member). So, when the start() method finishes the variable d still holds a reference.

Discussion:
12 comments Page 2 of 2.

Nikhil said:   4 years ago
When a method is called it goes inside the stack frame. When the method is popped from the stack, all its members dies and if some objects were created inside it then these objects becomes unreachable or anonymous after method execution and thus becomes eligible for garbage collection.

Example

package garbagecollector;
public class NullifyObj {
public static void main(String[] args)
{
// TODO Auto-generated method stub
NullifyObj v = new NullifyObj();
v.show();
Runtime r =Runtime.getRuntime();
r.gc();
}
public void show() {
NullifyObj n = new NullifyObj();
}
public void finalize() {
System.out.println("nullify Method object");
}
}

Rahman said:   3 years ago
How option D is correct? Please explain me.


Post your comments here:

Your comments will be displayed after verification.