Difference between Heap and Stack memory, why can’t we store everything in stack?



“In Java, Stack memory holds primitives and method invocations and heap memory is used to store objects.”
The basic difference between stack and heap is the life cycle of the values.
Stack values only exist within the scope of the function they are created in. Once it returns, they are discarded.
Heap values however exist on the heap. They are created at some point in time, and destructed at another (either by GC or manually, depending on the language/runtime).
Now Java only stores primitives on the stack. This keeps the stack small and helps keeping individual stack frames small, thus allowing more nested calls.
Objects are created on the heap, and only references (which in turn are primitives) are passed around on the stack.
So if you create an object, it is put on the heap, with all the variables that belong to it, so that it can persist after the function call returns.
When a method is called , a frame is created on the top of stack.
Once a method has completed execution , flow of control returns to the calling method and its corresponding stack frame is flushed.
Local variables are created in the stack
Instance variables are created in the heap & are part of the object they belong to.
Reference variables are created in the stack.

No comments:

Post a Comment