ProLesson 10.2Advanced3 min readUpdated 30 October 2026
Heap, stack and metaspace
Where your variables and objects really live, what goes on the stack versus the heap, and the errors you get when each runs out.
"Where is this stored, stack or heap?" is a classic question. The rule is simple once you see it in one example.
01The rule
- Stack: method calls and their local variables: primitives, and references to objects.
- Heap: the objects themselves, arrays, and their fields.
- Metaspace: class information: method code, field definitions, the constant pool.
java
class Order {
double amount; // field → inside the Order object, on the heap
static int created; // static field → with the class data (on the heap since Java 8)
}
void checkout() {
int items = 3; // primitive local → stack
Order order = new Order(); // reference "order" → stack; the Order object → heap
String note = "gift"; // reference → stack; "gift" → string pool, on the heap
}text
STACK (thread main) HEAP
┌──────────────────────┐ ┌───────────────────────┐
│ checkout() frame │ │ Order { amount = 0.0 } │◄─┐
│ items = 3 │ │ "gift" (string pool) │◄┐│
│ order ──────────────┼─────────┼────────────────────────┼┼┘
│ note ──────────────┼─────────┼────────────────────────┼┘
├──────────────────────┤ └───────────────────────┘
│ main() frame │
└──────────────────────┘Loading the rest of the lesson…