Stack vs Heap Memory in Java

1. Introduction

In Java, memory is mainly categorized into 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.
Smaller size compared to heap memory. Running out of stack memory results in a StackOverflowError. Much larger in size, but running out of heap space results in an OutOfMemoryError.
Each thread in a Java application has its own stack, which is not accessible by other threads. All threads share the heap, making it a central storage area for all parts of your Java application.
Ideal for temporary variables or references created and accessed in a method scope. Suitable for storing objects that need to be accessed across several methods or shared between multiple threads.
Does not require garbage collection; variables are automatically freed up when the block of code (method) finishes execution. Requires garbage collection to free up unused objects, which can be an overhead if not appropriately managed.

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
        System.out.println(localValue);
        System.out.println(obj);
    }
}

Output:

10
java.lang.Object@15db9742

Explanation:

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

2. obj is an instance of an 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.

Comments