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.
About Question com.enthuware.ets.scjp.v6.2.431 :
Moderator: admin
-
- Site Admin
- Posts: 10385
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question com.enthuware.ets.scjp.v6.2.431 :
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.
The object may be GCed anytime after hello() method returns.
-
- Posts: 2
- Joined: Sun Aug 24, 2014 4:30 pm
- Contact:
Who is online
Users browsing this forum: Google [Bot] and 14 guests