• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Strings and GC

 
josephine chen
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 = new String("hello");
String b= new String("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) - -----true
D)The line marked(4)
E)The line marked(5)
 
ShreeDevi
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Should it be after line 2 is executed, just before line 3?
 
Jerson Chua
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the answer should be on line marked with 4 since d has a reference on "bye". On line (marked 3), d is assigned to a,
So it is after line (marked 3), the "bye" is eligible for garbage collection.
 
paul wheaton
Trailboss
Pie
Posts: 21338
Firefox Browser IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer is C.
I think you guys aren't getting much response to this because this question was thoroughly discussed just a few days before you posted this.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jerson- You are correct in stating it's eligible after line 3. Note that the question says "Which is the earliest line in the following code after which the object [will be GC'd]". That means if you answer 4, it means "after line 4", which is incorrect. Even though 4 is after 3, the "after" part is already built into the question, so they're looking for the answer 3.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic