• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

can anyone explain this?

 
lavanya sankuappan
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given the following code, how many objects will be eligible for garbage
collection on the line with the comment //here
public class BettyAck {
public static void main(String argv[]){
BettyAck b =new BettyAck();
}
public BettyAck() {
Integer x = new Integer(10);
findOut(x);
Integer y = new Integer(99);
Integer z = y;
z = null;
findOut(y);
//here
}
public void findOut(Integer y){
y = null;

}
}
 
Henry Wong
author
Marshal
Pie
Posts: 21420
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
At the point "//here", the betty object has almost completed construction. It also created two integer objects. One is still referenced by x. The other is still referenced by y. And both local variables are still in scope...

So nothing should be eligible for GC.

Henry
 
Craig Jackson
Ranch Hand
Posts: 405
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
At the time the thread reaches the "//here" line of code, wouldn't the object "z" be eligible for GC, since it is no longer pointing toward "y"?

The object "y" will still contain the value 99, but z will not, because it is no longer pointing to "y".

Advise.
 
Pramila Chinguru
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
isn't z available for GC?
 
Henry Wong
author
Marshal
Pie
Posts: 21420
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Craig Jackson:
At the time the thread reaches the "//here" line of code, wouldn't the object "z" be eligible for GC, since it is no longer pointing toward "y"?

The object "y" will still contain the value 99, but z will not, because it is no longer pointing to "y".

Advise.


References are *not* garbage collected, the objects that they refer to are... The integer object 99 had two references to it. It lost one when the z variable was set to null. It will be eligible for garbaged collection, when the other variable, y, goes out of scope.

Henry
[ June 02, 2006: Message edited by: Henry Wong ]
 
lavanya sankuappan
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Henry for your quick reply
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic