The JVM picture: stack frames meet the heap
Two memory regions, two very different rules
The single most important diagram in Java has two boxes. On the left, the stack: a strict last-in, first-out region that grows and shrinks with method calls. On the right, the heap: a larger, garbage-collected region where every object lives for as long as something still refers to it. Almost every concurrency bug, performance surprise, and "why did my object change?" question can be explained by this diagram.
The stack
Every time a method is invoked, the JVM allocates a stack frame for it. The frame stores the method's parameters, local variables, operand stack used by the bytecode, and a return address. When the method returns, the frame is popped — its locals cease to exist. Deeply nested calls make the stack tall; infinite recursion makes it fall over with StackOverflowError.
The heap
Every object you create with new, every array, every String literal (in the string pool) lives on the heap. A local variable of a reference type does not contain the object — it contains a reference to it. Multiple references can point at the same object; the garbage collector reclaims an object only after every reference to it is gone.
class StackHeapDemo {
public static void main(String[] args) {
int counter = 0; // primitive value in main's stack frame
Customer c = new Customer("Ada"); // reference in frame, object on heap
rename(c);
System.out.println(c.name); // prints "Ada (edited)" — same heap object
}
static void rename(Customer ref) {
ref.name = ref.name + " (edited)"; // mutates the heap object via the reference
ref = new Customer("Z"); // rebinds the local only; caller's ref unchanged
}
}
class Customer {
String name;
Customer(String name) { this.name = name; }
}Why this matters every day
- NullPointerException means "you followed an arrow that pointed at nothing."
- Aliasing: two references pointing at the same object mean a mutation via one is visible via the other.
- Escape analysis and stack allocation: the JIT sometimes proves an object does not escape and puts it on the stack.
- Concurrency: visibility is about when one thread's writes to a heap object become visible to another.
Takeaways
- The stack holds frames with primitives and references; the heap holds objects.
- A reference is an arrow — assignment redirects the arrow, it does not copy the object.
- Almost every "weird" Java behavior has a clean explanation in this diagram.
Enjoying This Lesson?
Your support helps create more comprehensive courses and lessons like this one. Help me build better learning experiences for everyone.
Support Awashyak