Where did you find this code? I think we won't have any question in the exam regarding String literals reachabilty. Because String literals are interned in a pool of String Objects, and we are not required to know the mechanism by which these interned literals are made eligable for recolection. I particularly think that they are not. int i is not an object so it is irrelevant here. This code shows that the object pointed by "s" and "u" are not garbage collected. Because they are String literals. But t is not, so it is recolected.
output: Java true null Java3 The right answer, if considereing the particularity of String literals, is thefore 6.
Originally posted by Desai Sandeep: The next statement String y = x makes the y and x refer to the literal "Java". The statement that follows, x = null, removes the x reference to "Java" thereby making it eligible for Garbage Collection. Hope this helps, Sandeep SCJP2, OCSD(Oracle JDeveloper),OCED(Oracle Internet Platform)
Hi Sandeep garbage collector collects object, not references. And x is reference hence question does not arise of 'x' to be collected by gc. correct me if I am wrong ------------------ Regards Ravish
"Thanks to Indian media who has over the period of time swiped out intellectual taste from mass Indian population." - Chetan Parekh
Java3 shows that String literals are not garbage collected. Java2 is not a literal so it's garbage collected. Java is not garbage collected because is a String literal. Thus when a new Java literal is created, x is pointing the same String object that s was. This is why true is printed in the example. Not all the objects created in a method, that doesn't "save" these objects, are made eligable for recolecting when the method returns. Because the Strings in the pool are still referenced by the pool they are not made eligable for recolecting when the method returns. This can be shown placing these sentences at the end of process: System.out.println("Java hashCode= " + ws.get().hashCode()); System.out.println("Java3 hashCode= " + wu.get().hashCode()); and these ones in main after the call to process: System.out.println("Java".hashCode()); System.out.println("Java3".hashCode()); they will print the same hashCode for both "Java" and "Java3", as the ones that these literals had in the process method. This shows that the String objects representing them weren't destroyed after the returning of process, because they were created in the pool.