Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

garbage collection

 
David G Harris
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Hi guys, a Self Test question on page 269 of Sun Certified Programmer for Java 6 says

class CardBoard {

Short story = 200;
CardBoard go (CardBoard cb) {
cb = null;
return cb;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CardBoard c1 = new CardBoard();
CardBoard c2 = new CardBoard();
CardBoard c3 = c1.go(c2);
c1 = null;
if (c3 == null)
System.out.println("c3 is null");

}
}

The question is, "How many objects are eligible for garbage collection and the answer given, is 2 - c1 and c1.story. How come c3 isn't eligible?
 
Adolfo Eloy
Ranch Hand
Posts: 146
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi David.

The c3 variable is referring to null.
It was never referring to any object.
So you do not need to worry about c3 variable.

The point is:
reading the question at K&B. when // doStuff is reached, only the object that was referenced by c1 will be eligible for GC.
Regarding the instance variable story of type Short that belongs to CardBoard we need to consider 2 instances eligible.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic