Page 1 of 1

About Question com.enthuware.ets.scjp.v6.2.431 :

Posted: Fri Mar 18, 2011 5:19 pm
by ETS User
Hi,

I was wondering what happens if the method argument is not a reference of an object created outside the method, but instead is created "on the spot". For e.g.

class SayHello{

void hello(SayHello s){
System.out.println("hello");
}

public static void main(String[] args){

SayHello sh=new SayHello();
sh.hello(new SayHello());

}

}


Here instead of passing a reference to the SayHello object in hello(), we're creating the argument in the method itself. Will such an object be garbage collected? Thanks.

Re: About Question com.enthuware.ets.scjp.v6.2.431 :

Posted: Fri Mar 18, 2011 9:21 pm
by admin
In case of sh.hello(new SayHello()); yes, the object will be GCed but not in hello() method. The object was created in the calling method and even though you do not see a reference to the object stored in a variable, the JMV puts a reference to it in the thread's method stack. A copy of this reference will be passed to hello() method.
The object may be GCed anytime after hello() method returns.

Re: About Question com.enthuware.ets.scjp.v6.2.431 :

Posted: Wed Aug 27, 2014 9:34 pm
by eattok
Thanks!