Memoryeasy0-2 years

A method's local variable disappears the instant the method returns, but an object created inside that same method can still be alive minutes later. Why do these two things, created in the same line of code, have such different lifetimes?

They live in two different regions of memory with two different rules for when something dies. The stack holds a method's locals and where to return to; it's small, one per thread, and a frame dies the instant the method returns — nothing decides that, returning is what kills it. The heap holds everything you create with new; it's shared by every thread, much larger, and something has to actively decide a piece of it is no longer needed. In Java that something is the garbage collector, and it only reclaims an object once nothing can reach it anymore — which can be long after the method that created it has returned, if something else (a field, a list, a caller) still holds a reference.

The lesson behind it →