I am reading the SCJP 6.0 Certification book from Kerry and Kathy and I have a doubt I can't clarify with the book info. I googled but I didn't found any info about that. My question is about the JVM garbage collector.
The book explains this: "local variables are in the stack and instance variables / objects in the heap. When a method finalizes and returns: local variables are eligible for garbage collection", but my question is: what about the object instantiated in the method ? Is automatically eligible for garbage collection also ?
if I have the same example but in a for statement like this:
Objects created with local variables are always eligible for garbage collection unless the reference to that object is passed outside the scope of that variable.
In the above case, the scope of s is the method body only. But as this method returns the object reference in a return statement, the object will not eligible for
GC after the execution comes out of the method body.
But in the above code, the object refernced by s will be eligible for GC once the execution comes out of the method body as this object is not referenced furthur.
Hope this helps.
When it's obvious that you have to do it, just do it without shattering your thoughts over different directions.