Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Garbage Collection

 
Roll
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Q]Which is the earliest line in the following code after which the object created on the line marked(0) will be a
candidate for being garbage collected, assuming no compiler optimization are done?
public class Q76a9 {
static String f() {
String a = "hello";
String b= "bye"; //0
String c = b + "!"; //1
String d = b;
b = a; //2
d = a; //3
return c; //4
}
public static void main(String args[]) {
String msg = f();
System.out.println(msg); //5
}
}
A)The line marked(1)
B)The line marked(2)
C)The line marked(3)
D)The line marked(4)
E)The line marked(5)
Is it line3) because line0) hets garbage collected after line2).
So, i think c) should be correct , but some say's it as B).
Any comments or suggestions?
 
paul wheaton
Trailboss
Pie
Posts: 21341
Firefox Browser IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'll go with B because in the question it says "Which is the earliest line in the following code after which ..." For me the "after which" makes all the difference.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think it should be C) line three. Here is my reasoning:
The object created in line 0 is a String object containing the letters "bye". Later, the variables b and d both refer to this object. After line two, the variable d still refers to this object, so it can't be garbage collected. After line three, there are no variables referring to that String object, so it could be garbage collected.
 
paul wheaton
Trailboss
Pie
Posts: 21341
Firefox Browser IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Excellent point. You are correct.
Just to mess things up a bit more... The question is obviously designed to find a particular answer. But the question is errant. b references a string constant that is in the String Pool before the program is started. Therefore, it is never garbage collected. This particular example would be better if it had the line b = new String("bye");
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can any java Guru explain What is meant BY "assuming no compiler optimization are done?" what implication it has on the Question??
thanks
Sharana
 
rajsim
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The smart optimizing compiler could replace the entire
code with the following code without affecting the results.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic