Skip to content
Advertisement

Why are reference types stored in heap

I do know that in Java, (perhaps in .net too) , primitives are stored on stacks , where as reference types are stored on heaps.

My question was that I do not understand the proc/cons for this behavior. Why can’t we reference a memory location inside our stacks instead? . I couldn’t find a proper explanation as I googled ( maybe I suck at it) , but if you people can provide some insights I would be grateful

Thanks.

Answer

You can’t generally store reference types on stack because the stack frame is destroyed upon method return. If you saved a reference to an object so it can be dereferenced after the method completes, you’d be dereferencing a non-existent stack location.

The HotSpot JVM can perform escape analysis and, if it determines that an object cannot possibly escape the method scope, it will in fact allocate it on the stack.

Advertisement