What is the difference between heap and stack?


I'm a novice Java developer and just getting my feet wet with memory management. Can someone explain heap vs stack and how these work?

Your thoughts?

devDoctor |

The JVM allocates a specified amount of memory to your application when it starts up. This is the heap space reserved for storing objects, classes, and methods defined in your application. The heap is a global space and is not considered thread safe.

It is the stack that accesses the heap space in a thread safe manner. The stack works by creating memory blocks when method execution begins. This block holds primitive data types as well as REFERENCES to things stored on the heap.

This allows objects stored in the heap to be accessed by multiple methods without adding unnecessary memory usage to your application.

FewerLinesThanYou | 0

The difference between heap and stack is how the memory is used.

Heap memory is used to store objects you create when your program executes. It exists as long as your application is running.

Stack memory is used to store primitive data types and references (to things stored in the heap) when your program executes. It is thread specific.

Blocks of memory are added and removed from the stack as your program executes. They are created in a LIFO (last in first out) fashion when a method is invoked. They are released when the method has finished execution.

BuiltOnJavaScript | 0

Heap is much larger than stack. Heap is dynamically managed via garbage collection process. Stack is automatically managed via method execution.