This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes can anyone explain this? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "can anyone explain this?" Watch "can anyone explain this?" New topic
Author

can anyone explain this?

lavanya sankuappan
Greenhorn

Joined: Jun 02, 2006
Posts: 17
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
Sheriff

Joined: Sep 28, 2004
Posts: 18765
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Craig Jackson
Ranch Hand

Joined: Mar 19, 2002
Posts: 405
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

Joined: May 05, 2006
Posts: 54
isn't z available for GC?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18765
    
  40

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

Joined: Jun 02, 2006
Posts: 17
Thanks Henry for your quick reply
 
wood burning stoves
 
subject: can anyone explain this?