Here is a method which creates a number of String objects in the course of printing a count down sequence. When the program reaches line 8, how many of the String objects created in line 5 are eligible for garbage colloection?
A. none B. 1 c. 10 D. 11
My take is D, but the answer is C. The explanation is because only the last String object of the 11 created still has reference.
My question is the tmp variable is difined in the for loop. When out of the loop, tmp will not exist. How can it hold the last object?
Does the variable go out of scope when it exits the loop or when it exits the method ? I remember having read somewhere, in javaranch, that objects are available for garbage collection not immediately, but only when they come out of the method. Please correct me if otherwise.
Joined: Jul 13, 2004
And to add on to my previous post, in this scenario i believe there would not be any garbage collection taking place since the objects do not get created in the heap. This was tested through JProbe.
Joined: Oct 12, 2000
Whenever there are no more references to an object does it get eligible for garbage collection. For objects that don't loose a reference inside a method, this happens when the method terminates (unless an object is in the method placed in a collection that has a reference outside the collection or the object is returned from the method, in which case the object will survive the method.
Joined: Mar 13, 2004
In the given code, tmp is a local variable in the block which is the body of the for statement. When the loop ends and line 8 is reached, the variable is out of scope.
As for String objects going on the heap, the only time we know they are unique objects on the heap is when new is used.
The only times we know the String objects are not on the heap are when a String literal or other constant expression is used, when a String method is used on a String object in the constant pool and no change to the String object occurs ("abc".trim()), and when String.intern() has been used on a String object.
The above guaranteed cases are fair game for the exam, more likely using the == operator than using System.gc(). That leaves many cases that are implementation dependent and therefore should not be on the SCJP exam.