Java Heap vs Stack?


What’s the difference? Why???

Your thoughts?

Ron Shepard /

Heap space is allocated to your Java application at runtime. This memory is reserved for dynamically allocating/releasing memory needed for creating objects and JRE classes your application uses. Whenever you do something like new Object() it's stored in the global heap space.

Stack memory is specific to a single thread. When your methods execute, a block of memory is added to the top of this stack. It stores primitive data types as well as references to objects stored in the heap. When the method finishes execution, this block of memory is released from the stack.

By storing objects on the heap space, Java can automatically manage shared references to use memory as efficiently as possible.

Additionally, garbage collection is performed on the heap space to free up unused memory. This is what allows Java programmers to write code without having to manually manage memory allocation.

SherryAtkins /

Heap space is global memory space used to store all of the objects and classes you define in your program.

Stack memory is thread specific and used for method execution.

Stack memory holds references to things stored in heap memory

WHY? This maximizes the efficiency of memory allocation and allows garbage collection to automatically handle memory allocation for you...

Tech Lead 101 /

Heap memory stores shared objects used by the application. It is not thread safe.

Stack memory stores references to objects in the heap. It also stores temporary variables used in methods etc. Stack memory automatically releases allocations when methods are finished executing. Stack memory is faster to access than heap memory and is thread safe.

heap memory relies on garbage collection to free memory for your application. Heap memory is slower to access but has significantly more space than stack memory

SwiftOverJava /

Stack memory is “localized” to methods. It automatically releases the memory used for method variables etc once the method is done executing.

heap memory is “global” memory. It’s managed by garbage collection and is generally slower to access than stack memory.

JavaLava /

Let’s say your program executes a method. This method creates a “User” object.

The memory needed to run this method is allocated to stack memory. It’s specific to the method and releases automatically when the method finishes executing.

The “user object” that gets created is stored in the heap (global) space. References to this object are stored in the stack.

imDifferent /

Heap memory exists as long as your program executes. Stack memory exists in blocks only as long as a method executes.

Heap space is global and stores objects you declare. It is not thread safe. Stack memory is local to a specific method. It is thread safe.

Heap memory is much greater than stack memory but heap memory is slower to access than stack memory.