Stack vs Heap Memory in Java

1. Introduction

In Java, memory is mainly categorized into two types: Stack and Heap. The Stack is the area of memory where method invocations and local variables are stored. The Heap is the area of memory used for dynamic allocation, where all the objects (and their instance variables) are stored.

2. Key Points

1. Stack memory is used for execution of threads, storing local variables and method call stacks.

2. Heap memory is used to store objects in Java.

3. Stack memory is automatically allocated and deallocated when a method is called and returned respectively.

4. Heap memory management is based on the generation associated with each object.

3. Differences

Stack Memory Heap Memory
Stores primitive variables and references to objects. Stores all created objects in Java.
The life of a variable in the stack is limited to the scope of its method. Objects in the heap have global access and can be accessed from anywhere.
Size is less when compared to the heap. The heap size is significantly larger than a Stack memory.
Has limited memory and can lead to StackOverflowError. Can lead to OutOfMemoryError if memory is full.

4. Example

public class MemoryExample {
    public static void main(String[] args) {
        int localValue = 10; // Stored in stack memory
        Object obj = new Object(); // Object stored in heap, reference stored in stack




1. localValue is a local variable and is therefore stored on the stack. When main method is called, space is allocated on the stack for localValue.

2. obj is an instance of Object, so it is stored in the heap, and the reference to obj is stored on the stack.

5. When to use?

- Stack memory should be used for short-lived variables and where size is known to be within certain limits.

- Heap memory is best used for objects that need to be shared across method calls and have a longer lifespan.