wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Garbage Collection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Garbage Collection" Watch "Garbage Collection" New topic
Author

Garbage Collection

Mamadou Touré
Ranch Hand

Joined: Dec 27, 2007
Posts: 189
This question is from the examulator

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;

}
}


Incorrect options are shown by strikethrough, any options you chose are marked by a tick
1 0
2 1
3 2
4 3
5 4

The Correct Answer is
1) 0
A reference passed into a method is passed as if it were a copy of a pointer rather than the actual object. Thus if that reference is assigned to a null it makes no difference to any other copy of that pointer. Thus the code within the method findOut makes no difference to any other references. Although reference z is assigned to null reference y still points to the object so no objects are eligible for garbage collection.


I have selected option 3 (2 objects). I would agree with the explanantion given here, if it comes to primitives, but Integer objects are not primitive, so when they are passed into a method any changes made on that copy should affect the original object as well. Am i right ?


SCJP 5 (76%)
SCWCD 5 (86%)
SCBCD 5(70%)
--------------------
"The greatest glory in living lies not in never falling, but in raising every time we fall.".. Nelson Mandela
Ralph Jaus
Ranch Hand

Joined: Apr 27, 2008
Posts: 342
The answer given in examulator is correct: x and y still refer to Integer objects (of value 10 resp. 99). Look what happens: But be carefull: Note: The variable y in the method could also be named x. That wouldn't change the result in neither of the two examples.
[ July 19, 2008: Message edited by: Ralph Jaus ]

SCJP 5 (98%) - SCBCD 5 (98%)
Mamadou Touré
Ranch Hand

Joined: Dec 27, 2007
Posts: 189
Thanks a lot Ralph,

It's clear in my mind now.
Milan Sutaria
Ranch Hand

Joined: Jul 10, 2008
Posts: 118
Thanks to you both. It helped me also


SCJP 6 83%
Working on SCWCD/OCPJWCD
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Garbage Collection
 
Similar Threads
Garbage Collection
q on threads
GC Question from Marcus Green
Object eligible for GC?
Garbage Collection