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

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
ETS User

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

Post 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.

admin
Site Admin
Posts: 10053
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post 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.
If you like our products and services, please help us by posting your review here.

eattok
Posts: 2
Joined: Sun Aug 24, 2014 4:30 pm
Contact:

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

Post by eattok »

Thanks!

Post Reply

Who is online

Users browsing this forum: No registered users and 46 guests