How many objects are eligible for garbage collection once execution has reached the line labeled Line A? -------------------------- String name; String newName = "Nick"; newName = "Jason"; name = "Frieda"; String newestName = name; name = null; //Line A
1) Initially name is pointing to null. 2) newName is pointing to "Nick" ,( Object creted in String Pool) 3) newName is pointing to "Jason" , ( -do-) so nothing is pointing(referring) to "NICK" 4) now name is pointing to "Frieda" (-do-) 5) newestName is also poining to "Frieda" 6) name is null ,but newestName is pointing to "Frieda" 7) So , only "NICK" can be gc'ed. regards Sateesh
Sateesh, Thank You very much for your clear explanation. I also had a doubt about this kind of questions.Thank a lot for helping me to clear my problem.
In the above piece of code the String literal "Nick" would not be garbage collected since this would go to the String pool. Can somebody throw some light on Garbage collection with respect to String pools ? Thanks Subbu
Hi, The JVM Maintains a String Pool... for example... 1: String s1="Hello"; 2: String s2="Hello"; 3: String s3=new String("Hello");
In Line 1, the JVM creates a String "Hello" (LITERAL), and passes the reference to s1. In Line 2, the JVM sees that another string "Hello" has to be created, instead of creating one, it passes the reference of the previously created String to s2. FOR EFFICIENCY. That's why (s1==s2) is true. The JVM maintains this pool.. consisting of strings created from only LITERALS. Hope you got the point. So you can see that (s2==s3) returns false. ANYBODY: is this correct? Bye
Hi You are right nutan. JVM maintain string pool of literals. In above example all are literals and no objects. As objectes are created with new operator, which is not done here. So will these literals will be garbage collected Pleaethrow some light on which one will be garbage collected Parag
I think the String literals in the string pool will not be garbage collected. But m doubt is will it be garbage collected only when the JVM is restarted ? Thanks Subbu
Subbu
I do some of my very best work in water. Like this tiny ad:
a bit of art, as a gift, that will fit in a stocking