public void method()
String str = new String("value");
} // Line 1
} // Line 2
When is the earliest that the str object can be garbage collected? Would it be after it falls out of scope within the nested blocks [ Line 1 ] or would it be after the method completes [ Line 2 ]. I don’t know if objects that are on the stack ( within a method call ) can be garbage collected or if they are unable to be garbage collected until the stack is returned ( the method completes ). Or maybe I am making this too hard
when its garbage collected no body nows, however you can know when its eligable for garbage collection, if it was another Object i would tell you that it gets eligable for garbage collection when it gets out of scope. however this is a String then i think it will not be garbage collected and it will be inserted in the String pool.
I am not 100% sure ;)
Omar Al Kababji - Electrical & Computer Engineer
[SCJP - 90% - Story] [SCWCD - 94% - Story] [SCBCD - 80% - Story] | My Blog
Just to organize what some of the other ranchers said:
1. An object is eligible for garbage collection when no active thread (in this case let's assume the only thread is the thread executing your method, the main thread) has an active reference (a reference which is accessible from your code) pointing to that object. So, in your case, the object becomes eligible for garbage collection after the reference str stops being an active reference. That happens when the code exits the block where str is declared. Line //1 closes the code block where str is declared, so after line //1 executes, you can say that one of the the String objects created (potentially, 2 objects were created, but the other one will be referenced from the String Constant Pool) is eligible for garbage collection. But that doesn't mean it will be garbage collected, as there are no guarantees on that.
2. Like Ravikanth said, objects are always created in the heap. Variables are another story (instance variables reside in the heap with the objects they belong to, as do static variables, whereas local references reside in the stack of the method they are declared in.)
All code in my posts, unless a source is explicitly mentioned, is my own.
Omar Al Kababji
Joined: Jan 13, 2009
Thats what i thought ... the "value" literal will be sitting there somewhere in the String pool... right ?
Joined: Dec 16, 2008
Yes, you are right Omar. I think that String objects which a referred to from references in the SCP can never be garbage collected, although there might be an advanced way to do that which I am unaware of. Nothing to consider for the exam though, I am sure.