• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Garbage Collection

 
Mamadou Touré
Ranch Hand
Posts: 189
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ?
 
Ralph Jaus
Ranch Hand
Posts: 342
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Mamadou Touré
Ranch Hand
Posts: 189
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Ralph,

It's clear in my mind now.
 
Milan Sutaria
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to you both. It helped me also
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic