Garbage collection on a local variable

It will be garbage collected at some point after it’s no longer used. I believe in current implementations of Java it will actually persist until the end of the method, whereas the garbage collector in .NET is more aggressive. (I don’t know whether there are any guarantees even in Java. Normally you’d only want the local variable to persist beyond its last possible read when you’re debugging.)

But no, you don’t need to set the variable to null, and doing so would harm readability.

It’s unlikely that the object will garbage collected immediately after the method exits; it’s up to when the GC runs… and of course if anything else holds onto a reference to the object, it may not be eligible for garbage collection anyway. Don’t forget that the value of the variable is just a reference, not the object itself. (That may take a while to get used to coming from C++.)

Leave a Comment