Hey everyone got a question on the following JQ+ question.
How many strings are eligible to be garbage collected after the execution of line 2 and line 4?
I said 1,3 the answer says 0,2 with this explaination
After execution of line 2, str0 points to "some string" and str1 becomes null. So "some string" is not hanging. Hence 0 objects are eligible for GC after line 2. After execution of line 3, str2 points to str0 (ie. "some string") and "second string" becomes hanging. After execution of line 4, str3 points to str2 (ie.again "some string") and "third string" becomes hanging. Hence 2 objects are eligible for GC after line 4.
My thinking is that on line 2 it sets str1 to null so that String object is available to be gc'd. Then after line 4 the other 2 (str2 and str3)are eligibe to be collected because they go out of scope when the method exits. The only point i'm not sure about is the literals in the pool, they aren't collected until the jvm exits right? Thanks Dave
The answer is right. Here you should know the difference of reference variable and object. In the question, there are 4 reference variables and 3 objects creating by "new". In line 1, reference variable str0 pointers to object1, so object1 are pointered by str0 and str1. In line 2, even if str1 is set to null, the object1 is still pointered by str0. So no object is OK for garbage collecting. The same thing happens in line 3 and line 4. Hope it helps.
Hi Dave, The answer is correct. A picture is worth a thousand words so here's a link to a diagram. Hope it makes it easier to see what's happening. ------------------ Jane Griscti Sun Certified Programmer for the Java� 2 Platform
Thanks Jane and Jason Had a momentary loss of memory there, I think I knew that. For some reason I wanted to think that the variables refered to objects that held the values of the strings but also the strings were objects themselves in the pool. I think i was thinking too hard about it thanks Dave
0 2 is correct. Line two merely reassigned a String reference to another. All String instances were still referenced. Line 3 assigned a String reference that was originally assigned to a different String instance to another String instance, the old String instance was no longer referenced. Same with line 4.
Joined: Aug 30, 2000
Hi Angela, I'm afraid I don't know of any sites with more info. The best way to practice is with the questions you run into on the mocks. A key to understanding how gc works is in understanding the difference between reference and primitive variables and what happens when they are passed to methods. Setting a reference parameter to a 'null' in a method is not the same as setting the original reference variable to 'null'. If you're getting them right don't worry to much. You'll probably only see one or two gc questions on the exam. Hope that's of some help. ------------------ Jane Griscti Sun Certified Programmer for the Java� 2 Platform