Stack vs Heap

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • Heap Space: Stores Objects and Instance Variables. It is a single, massive block of memory shared by all threads. Managed by the Garbage Collector.
  • Stack Memory: Stores Local Variables (primitives) and Method Calls. Every single Thread gets its own private, isolated Stack.

Concept

When you write int x = 5; inside a method, Java places that primitive directly onto the Thread Stack. The Stack operates strictly in a Last-In-First-Out (LIFO) order. As soon as the method finishes executing, its “Stack Frame” is instantly popped off, and all local variables are destroyed in nanoseconds. It is incredibly fast and requires no Garbage Collection.

When you write User u = new User(); inside a method, it’s a two-part process.

  1. The actual User object (with all its data) is created on the massive, shared Heap.
  2. A small reference pointer (u) is created on the Stack, pointing to the object on the Heap.
    When the method ends, the u pointer on the Stack is instantly destroyed. However, the User object remains floating on the Heap. Eventually, the Garbage Collector scans the Heap, realizes no pointers are pointing to that User anymore, and deletes it.

Examples

public class MemoryDemo {
    
    // Instance variables live on the HEAP, inside the MemoryDemo object.
    private int instanceVar = 100; 

    public void calculate() {
        // 'localVar' is a primitive. It lives strictly on the STACK.
        // It will be destroyed the exact millisecond this method ends.
        int localVar = 5; 
        
        // 'person' is a reference variable on the STACK.
        // The actual "Alice" object is allocated on the HEAP.
        Person person = new Person("Alice");
    }
}

Interview Questions

Q: What causes a StackOverflowError?
A: A Stack is a finite block of memory (usually 1MB per thread). Every time a method is called, a new “Stack Frame” is pushed onto the top of the stack. If a method calls itself recursively without a proper exit condition (an infinite loop of method calls), it pushes thousands of frames onto the stack until it physically runs out of memory, throwing a StackOverflowError.

Q: Are Java objects always created on the Heap?
A: Usually yes, but not always. Modern JVMs implement an advanced JIT compiler optimization called Escape Analysis. If you create a local object inside a method (e.g., Point p = new Point(1, 2);), and the JVM proves that the object never “escapes” the method (it isn’t passed to another method or thread), the JVM will secretly break the object apart and allocate its primitives directly on the Stack. This prevents the object from ever touching the Heap, completely bypassing the Garbage Collector for massive performance gains.