File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Number of objects eligible for GC Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Number of objects eligible for GC" Watch "Number of objects eligible for GC" New topic

Number of objects eligible for GC

Bill Clar
Ranch Hand

Joined: Sep 21, 2006
Posts: 163

This is a question posted in the "Java Developers" group on LinkedIn. I'm not the original author.

After line 14, how many objects are eligible for garbage collection?

According to the thread's author, the answer is 2, but I only count 1.

My understanding is that ob1 in Line 3 is a copy of a reference. When the reference changes at Line 5, c1 still maintains a reference to the object created in Line 11.

Therefore, the only object I see eligible for garbage collection is created in Line 05. It becomes unattached when c2 changes it's reference to c3 in Line 14.

Is my analysis incorrect?
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

I would say 3.

Since after line 14, c1, c2 and c3 all go out of scope, none of the three objects created have valid references anymore.

But I guess that depends on what exactly "after line 14" means.

Otherwise, I agree with your assessment, for whatever that is worth.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Bill Clar
Ranch Hand

Joined: Sep 21, 2006
Posts: 163

Oops. I forgot to include the method call that occurs after line 14. It's an unknown method so I had to remove it in order to compile.
Matthew Brown

Joined: Apr 06, 2010
Posts: 4543

Then I agree with you. c1 references the C created on line 11, and c2 and c3 both reference the one created on line 13. The one created by the method call on line 12 is the only one eligible.

(It would still be one even if Java was pass by reference, but it would be a different one!).
Bill Clar
Ranch Hand

Joined: Sep 21, 2006
Posts: 163

Thanks Fred and Matthew!
nweoo mon

Joined: Aug 29, 2012
Posts: 3
yes, i also agree with you
I agree. Here's the link:
subject: Number of objects eligible for GC
It's not a secret anymore!