Stack vs Heap

In this post, we will learn the difference between Stack and Heap in Java. This is a frequently asked
question in Java interviews for beginners. Let's dive into it.

Difference between Stack and Heap in Java

Stack Heap
Stack memory is used for the execution of a thread. Heap memory is used for dynamic memory allocation.
Stack memory is automatically managed by the JVM. Heap memory management is typically more complex, requiring manual allocation and deallocation.
Each method execution creates a new block in the stack memory for storing local primitive values and references to other objects. Once the method execution is done, the block becomes unused and is ready for the next method. Objects are always allocated on the heap. The memory for any object is freed when the garbage collector runs.
Access to stack memory is fast because it's organized as a Last-In-First-Out (LIFO) data structure. Access to heap memory is slower because it involves pointers to the objects that reside in the heap memory.
Stack memory is limited and too many method calls (like in the case of recursive calls) or very large-sized local variables may lead to a StackOverflowError. Heap memory is typically larger and limited by the size of addressable memory (or by a parameter to the JVM). However, if it gets full, it will result in an OutOfMemoryError.
Variables in stack memory are thread-safe as each thread operates in its own stack. Objects on the heap are globally accessible, so not inherently thread-safe and need to be handled properly in a multithreaded environment.
Stack memory life cycle is controlled by individual threads. Heap memory is shared among all threads.
Memory allocation in Stack is done in a contiguous block. Heap memory is dynamically allocated, hence fragmentation is possible.