File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

q on garbage collection

 
JayaSiji Gopal
Ranch Hand
Posts: 303
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
void method X() {
String r = new String("abc");
String s = new String("abc");
r = r+1; //1
r = null; //2
s = s + r; //3
} //4

when is s eligible for garbage collection?

Before statement labeled 1
Before statement labeled 2
Before statement labeled 3
Before statement labeled 4
Never

i answered never, but the correct answer is 'before statement labeled 4'.
I didnt understand yy?
is is bcos s = s + r and r = null. anything added to null is null?
 
navneet shrivastava
Ranch Hand
Posts: 39
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, it is so bcoz 's' is a local variable (local to the method) so its scope is within the method. So, it wud be eligible for gc as soon as method ends.
 
Muralidhar Mandapati
Greenhorn
Posts: 23
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check the life of the variable. Since the variable s is a local variable , it does not exists outside the method and hence it should be eligible for garbage collection. Note that the question says it is eligle for garbage collection but not forcing the garbage collector to take the object.


Cheers,
Murali
 
Atul Chandran
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
s = s + r;
The above line will produce a new String literal "abcnull" and s will be referring to this new object. The String object "abc" referred to by s previously will be eligible for garbage collection.

Note in the question it is given as "Before statement 4" and local variables become eligible for garbage collection only after statement 4.
 
PNS Subramanian
Ranch Hand
Posts: 150
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Agree with Atul's comment.
The question talks about the original object pointed to by s. Local variables are available for gc once the method ends - i.e NOT before line 4.
Please correct me if otherwise.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic