Skip to main content

Command Palette

Search for a command to run...

Stack vs Heap

Updated
2 min read
Stack vs Heap

0. Introduction

Understanding the difference between Stack and Heap memory is one of the most fundamental concepts in Java. In this article, we will explore how Stack and Heap work, and the difference between them.


1. What is Stack Memory?

Stack memory is used for method execution. Each thread has its own stack, which makes it thread-safe by design.

1.1. What is stored in the Stack?

  • Local variables

  • Method parameters

  • Reference variables (the reference itself, not the object)

  • Stack frames (one per method call)

Every time a method is called, a new stack frame is created. When the method finishes, the frame is automatically removed.

1.2. Key Characteristics

  • Thread-specific

  • LIFO structure

  • Very fast allocation and deallocation

  • Automatically managed

  • Limited size

If too many stack frames accumulate, a StackOverflowError occurs.


2. What is Heap Memory?

Heap memory is used to store objects created using the new keyword. Unlike Stack, Heap memory is shared among all threads.

2.1. What is stored in the Heap?

  • Objects

  • Instance variables

  • Arrays

  • Static variables (in the method area, part of heap in modern JVM implementations)

Heap memory is managed by the Garbage Collector.

2.2. Key Characteristics

  • Shared among threads

  • Larger than stack

  • Slower allocation compared to stack

  • Managed by Garbage Collector

If too many objects are created and not properly reclaimed, an OutOfMemoryError may occur.


3. Stack vs Heap Comparison

Feature Stack Heap
Scope Per thread Shared across threads
Stores Local variables, references Objects, instance data
Speed Faster Slower
Memory size Smaller Larger
Management Automatic (method-based) Garbage Collector