In the following SCJP Mock Exam question, students are asked to find the exact line that String b
of the line marked (0) will be a candidate for Garbage Collection.
public class Q76a9 {
static String f() {
String a = "hello";
String b = "bye"; // (0)
String c = b + "!"; // (1)
String d = b; // (2)
b = a; // (3)
d = a; // (4)
return c; // (5)
}
public static void main(String[] args) {
String msg = f();
System.out.println(msg); // (6)
}
}
After finding out that the correct answer is 6, i came to the conclusion that if the String objects that are being stored in String Literal Pool lose their reference, don't countinue to be preserved in the Pool any more. If they are not referenced, they are eligible for Garbage Collection.
Is that true? If yes, how does the Literal Pool mechanism treats to Strings without any references?
Edit : The question assumes that no compiler optimizations are being done.