aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Garbage Collection Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Garbage Collection Question" Watch "Garbage Collection Question" New topic
Author

Garbage Collection Question

Nart
Ranch Hand

Joined: May 28, 2002
Posts: 95
hi... i am not sure about the answer to this Q
could someone please help me out with an exaplanation..
class Test
{
public static void main(String[] args)
{
for(int c = 5; c >= 0; c--)
{
Integer x = new Integer(c);
}
System.out.println("End");
}
}
When the program reaches System.out.println, how many Integer objects are eligible for garbage collection?
will it be 5 ? someone told me it would be zero.. so am not quite sure
Anthony Villanueva
Ranch Hand

Joined: Mar 22, 2002
Posts: 1055
Hi Nart,
An object is eligible for garbage collection if no references point to it. Inside the for loop you created 5 Integer objects, referenced one at a time by the reference x per iteration of the loop. Note that you declared x inside the for loop.
By the time you exit the loop the reference x goes out of scope, so the last Integer object (as well as the preceding ones) are no longer referenced. Therefore, they should be eligible for garbage collection.
HTH
John Held
Greenhorn

Joined: Jun 13, 2002
Posts: 13
It sure seems like it out to be six objects
to me. -- not an expert though.


John Held
Anthony Villanueva
Ranch Hand

Joined: Mar 22, 2002
Posts: 1055
No, you're right, there will be six iterations.
Nart
Ranch Hand

Joined: May 28, 2002
Posts: 95
hmmm.... won't the sixth Integer created be still be referenced? and the other 5 before it will be garbage collected?
Anthony Villanueva
Ranch Hand

Joined: Mar 22, 2002
Posts: 1055
The x reference is local to the for loop. Once you exit the loop, x goes out of scope. Try this:

The compiler will complain because the JVM no longer recognizes x, so it's not valid reference anymore.
 
Don't get me started about those stupid light bulbs.
 
subject: Garbage Collection Question