Is the stack garbage collected in Java?

The heap memory is garbage collected in Java.

Is the stack garbage collected as well?

How is stack memory reclaimed?


The memory on the stack contains method-parameters and local variables (to be precise: the references for objects and variables itself for primitive types). That will be automatically removed if you leave the method. If the variables are references (to objects) the objects itself are on the heap and handled by the garbage collector.

So the stack isn't garbage collected in the same way as the heap, but stack is a form of automatic memory-management in it's own (which predates garbage collection).

A more detailed answer is given by Thomas Pornin, look into that for more details.


The stack is not garbage collected in Java.

The stack allocated for a given method call is freed when the method returns. Since that's a very simple LIFO structure, there's no need for garbage collection.

One place where the stack and garbage collection interact is that references on the stack are GC roots (which means that they are the root references from which reachability is decided).