|
We saw in chapter 1 how the Java local variables are created on stack. When a method or block exits, these variables are discarded. If you have a method local variable storing an object reference, it too is discarded from the stack after the method finishes its execution. Therefore, the object referenced by it may become eligible for garbage collection. There are exceptions, however. For instance, if such object reference is returned from the method, then the referenced object will not be garbage collected. Let’s see how this works. In listing 6.4, the method getMyCar() creates two objects, a Car object and a Date object.

References to both of these objects are assigned to local reference variables. The Date object is eligible for garbage collection as soon as the method finishes. But the method returns a reference to the Car object. This returned reference is assigned to mycar. Therefore, the Car object is reachable through mycar. Hence it is not eligible for garbage collection even after the method getMyCar() has completed its execution. Note that in the method, you need not explicitly set the Date object’s reference to null to make it eligible for garbage collection. It becomes implicitly eligible for garbage collection after the method returns.