File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Strings and GC Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Strings and GC" Watch "Strings and GC" New topic

Strings and GC

josephine chen
Ranch Hand

Joined: Oct 29, 2002
Posts: 216
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)

Joined: Feb 02, 2000
Posts: 23
Should it be after line 2 is executed, just before line 3?
Jerson Chua
Ranch Hand

Joined: Feb 08, 2000
Posts: 68
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

Joined: Dec 14, 1998
Posts: 20972

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.

permaculture Wood Burning Stoves 2.0 - 4-DVD set
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
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.

"I'm not back." - Bill Harding, Twister
I agree. Here's the link:
subject: Strings and GC
It's not a secret anymore!