Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Garbage Collection Question

 
Nart
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It sure seems like it out to be six objects
to me. -- not an expert though.
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, you're right, there will be six iterations.
 
Nart
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic