Memory: stack vs heap

Junior Always asked 7 min

On this page

The question

Where do objects and local variables live in Java, and how do the stack and the heap differ?

30-second answer

Each thread has its own stack. Every method call pushes a frame holding its parameters and local variables: primitives as values, objects as references. Returning pops the frame. Objects and arrays live on the heap, which all threads share, and the garbage collector frees them once nothing references them. So a local Point p sits in a frame, and the Point it points at sits on the heap.

Understand it

Frames on the stack, objects on the heap

Step by step

main runs. Its frame holds the int n = 99 itself and a reference p to a Point object on the heap.

Step 1 of 5
View as text

The drawing has the thread's stack on the left, the heap on the right and the current line of code on top. Each frame on the stack lists its variables; a reference is drawn as an arrow from the frame to an object on the heap.

main runs. Its frame holds the int n = 99 itself and a reference p to a Point object on the heap. The heap holds one Point with x = 1, y = 2.

move(p, n) pushes a new frame. Its parameters are copies: x copies 99, and q copies the reference, so it points at the same Point. The move frame sits on top of main, and two arrows, from p and from q, meet at the one Point.

q.x = x writes through the copied reference, so the one shared Point on the heap now has x = 99.

move returns and its frame is popped. p still points at the same object, so main's p.x is 99. Only the main frame is left.

p = null removes the last reference. The Point is unreachable, so the garbage collector may reclaim it. The cell now reads p = null, no arrow reaches the faded Point, and it is marked unreachable.

The drawing has the thread's stack on the left, the heap on the right and the current line of code on top. Each frame on the stack lists its variables; a reference is drawn as an arrow from the frame to an object on the heap.

main runs. Its frame holds the int n = 99 itself and a reference p to a Point object on the heap. The heap holds one Point with x = 1, y = 2.

move(p, n) pushes a new frame. Its parameters are copies: x copies 99, and q copies the reference, so it points at the same Point. The move frame sits on top of main, and two arrows, from p and from q, meet at the one Point.

q.x = x writes through the copied reference, so the one shared Point on the heap now has x = 99.

move returns and its frame is popped. p still points at the same object, so main's p.x is 99. Only the main frame is left.

p = null removes the last reference. The Point is unreachable, so the garbage collector may reclaim it. The cell now reads p = null, no arrow reaches the faded Point, and it is marked unreachable.

Takeaway: Each call pushes a frame of parameters and locals on its thread's stack. Objects live on the heap, reached only through references the frames hold.

Can swap(p, q) swap the caller's points?

Predict

p points at a Point with x = 1 and q at one with x = 2. main calls swap(p, q), which runs t = a; a = b; b = t.

After swap(p, q) returns, what are p.x and q.x?
View as text

The drawing shows the method void swap(Point a, Point b) { Point t = a; a = b; b = t; } on top, the stack on the left and the heap on the right, with arrows from each reference on the stack to the Point it points at.

p points at a Point with x = 1 and q at one with x = 2. main calls swap(p, q), which runs t = a; a = b; b = t. The learner predicts p.x and q.x after the call.

The call pushes a frame for swap. a and b are copies of p and q, pointing at the same two Points. Each Point now has two arrows: one from main and one from swap.

Inside swap, a and b trade targets. p and q in main's frame still point where they did. The arrows from a and b cross; the arrows from p and q do not move.

swap returns and its frame is popped. p.x is still 1 and q.x still 2: Java passed the references by value.

The drawing shows the method void swap(Point a, Point b) { Point t = a; a = b; b = t; } on top, the stack on the left and the heap on the right, with arrows from each reference on the stack to the Point it points at.

p points at a Point with x = 1 and q at one with x = 2. main calls swap(p, q), which runs t = a; a = b; b = t. The learner predicts p.x and q.x after the call.

The call pushes a frame for swap. a and b are copies of p and q, pointing at the same two Points. Each Point now has two arrows: one from main and one from swap.

Inside swap, a and b trade targets. p and q in main's frame still point where they did. The arrows from a and b cross; the arrows from p and q do not move.

swap returns and its frame is popped. p.x is still 1 and q.x still 2: Java passed the references by value.

Takeaway: Java always passes by value. For an object the value is a reference, so a method can change the object but never which object the caller's variable points at.

Thread stacks and the shared heapThread main has a stack with the frames move and main. Thread worker has a stack with the frame run. Arrows lead from q in move, p in main and r in run to one Point object on the shared heap, so both threads reach it.worker stackmain stackmove: qmain: prun: rShared heap:one Point
Thread stacks and the shared heapThread main has a stack with the frames move and main. Thread worker has a stack with the frame run. Arrows lead from q in move, p in main and r in run to one Point object on the shared heap, so both threads reach it.worker stackmain stackmove: qmain: prun: rShared heap:one Point
Each thread has its own stack; all threads share one heap

In code

class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } }

static void move(Point q, int x) {
    q.x = x;      // writes to the Point that p also points at
    x = 0;        // changes only move's copy of n
}

public static void main(String[] args) {
    int n = 99;                         // the value sits in main's frame
    Point p = new Point(1, 2);          // p in the frame, the Point on the heap
    move(p, n);                         // a new frame with copies of p and n
    System.out.println(p.x + " " + n);  // 99 99
    p = null;                           // the Point is now unreachable
}
move() changes the shared object, not the caller's variables
static void swap(Point a, Point b) {
 Wrong     Point t = a; a = b; b = t;        // swaps the copies only
}
static void swapX(Point a, Point b) {
 Right     int t = a.x; a.x = b.x; b.x = t;  // writes through the references
}

Point p = new Point(1, 2), q = new Point(2, 2);
swap(p, q);
System.out.println(p.x + ", " + q.x); // 1, 2
swapX(p, q);
System.out.println(p.x + ", " + q.x); // 2, 1
Reassigning parameters swaps nothing; writing fields does
References during swap(p, q)The main frame holds p and q. The swap frame holds a and b, shown after they trade targets. p and b point at the Point with x = 1. q and a point at the Point with x = 2. The caller's references never moved.swap framemain framepqabPointx = 1Pointx = 2
References during swap(p, q)The main frame holds p and q. The swap frame holds a and b, shown after they trade targets. p and b point at the Point with x = 1. q and a point at the Point with x = 2. The caller's references never moved.swap framemain framepqabPointx = 1Pointx = 2
Inside swap(p, q): two frames, the same two Points
static int depth(int n) { return depth(n + 1); }   // StackOverflowError: one frame per call, never popped

List<byte[]> hog = new ArrayList<>();
while (true) hog.add(new byte[1_000_000]);         // OutOfMemoryError: Java heap space
Deep recursion fills the stack; an ever-growing list fills the heap

Solve it

Why won’t a lambda let you increment a local counter?

A candidate writes int count = 0; names.forEach(n -> count++); to count names, and the compiler says “local variables referenced from a lambda expression must be final or effectively final”. Explain the rule and fix the code.

  1. Locate the variable. count is a local, so it lives in the method’s stack frame. That frame is gone when the method returns.
  2. See what the lambda keeps. A lambda can outlive the frame, for example on another thread, so Java copies the local’s value into the lambda object on the heap.
  3. Explain the rule. If writes were allowed, the copy and the original would drift apart. Java forbids the write rather than let them disagree.
  4. Fix it. Let the stream count, or keep the state on the heap: an AtomicInteger whose reference never changes.
  5. Check. This is pass-by-value again: the lambda holds a copy of a reference and changes the object, never the variable.
int count = 0;
 Wrong names.forEach(n -> count++);                     // does not compile: count is a stack local

AtomicInteger counter = new AtomicInteger();     // the object lives on the heap
 Right names.forEach(n -> counter.incrementAndGet());   // the captured reference never changes

 Right long total = names.stream().count();             // simplest: no shared state at all
Capture a reference to a heap object, not a mutable local

How to answer

  • A call pushes a frame with its parameters and locals; returning pops it.
  • A primitive local holds its value in the frame; a reference local holds only a reference.
  • Objects, arrays and their fields live on the heap, including a primitive field such as int x.
  • Each thread has its own stack; all threads share one heap.
  • A frame's memory is freed when it pops; an object is reclaimed by garbage collection once it is unreachable.

Common mistakes

  • Saying an object created inside a method lives on the stack; only the reference is local, the object is on the heap.
  • Saying primitives always live on the stack, when a primitive field lives inside its object on the heap.

Follow-up questions

Is Java pass-by-value or pass-by-reference?

Always pass-by-value. A method receives a copy of each argument. For an object the copied value is a reference, so the method can change the object both variables point at, but reassigning its parameter never changes the caller's variable. That is why swap(p, q) cannot swap the caller's points, while q.x = 99 inside a method is visible to the caller.

  • Every argument is copied into the new frame, primitives and references alike.
  • Through a copied reference, a method can change the shared object's fields.
  • Reassigning a parameter changes only the copy; the caller's variable still points at the same object.
static void swap(Point a, Point b) { Point t = a; a = b; b = t; }
static void move(Point q) { q.x = 99; }

Point p = new Point(1, 2), q = new Point(2, 2);
swap(p, q); // p.x is still 1, q.x still 2
move(p);    // p.x is now 99

See it in the infographic: Can swap(p, q) swap the caller's points? See it in the infographic: Frames on the stack, objects on the heap

What is the difference between a StackOverflowError and an OutOfMemoryError?

A StackOverflowError means one thread's stack has no room for another frame, almost always from recursion that never stops or goes too deep. An OutOfMemoryError such as "Java heap space" means the heap cannot fit a new object even after garbage collection, because live objects fill it. Both extend VirtualMachineError, an Error, and are not meant to be caught and ignored.

  • StackOverflowError: one thread ran out of stack, typically from runaway recursion.
  • OutOfMemoryError: Java heap space: reachable objects fill the heap and garbage collection cannot free enough.
  • Fix the first with a base case or a loop; find the cause of the second in a heap dump.
  • -Xss sets the stack size per thread; -Xmx sets the maximum heap size.
static void down() { down(); }  // no base case
down();                         // java.lang.StackOverflowError

List<long[]> keep = new ArrayList<>();
while (true) keep.add(new long[1_000_000]);
// with -Xmx32m: java.lang.OutOfMemoryError: Java heap space

See it in the infographic: Frames on the stack, objects on the heap

Are local variables thread-safe?

A local variable lives in its own thread's stack frame, so no other thread can read or change it. But a local reference can point at a heap object that other threads also reach, and that object gets no protection from being referenced by a local. Locals are confined to their thread; the objects they point at are safe only if they never escape, are immutable, or are synchronized.

  • Each thread has its own stack, so its locals and parameters are never shared.
  • The heap is shared, so an object two threads reach needs synchronization or immutability.
  • A lambda captures a copy of a local's value, which is why the local must be effectively final.
int count = 0;
Runnable r = () -> System.out.println(count);
count++; // compile error: count must be final or effectively final

See it in the infographic: Frames on the stack, objects on the heap

Where do static variables live?

A static field belongs to the class, not to a frame or an object, so there is one copy per loaded class, shared by every thread. HotSpot stores its value with the class's java.lang.Class object on the heap; class metadata sits in Metaspace, outside the heap, since Java 8. An object a static field references stays reachable while the class is loaded.

  • One copy per class, shared by all threads, so writes need synchronization.
  • HotSpot keeps static values with the Class object on the heap and class metadata in Metaspace.
  • An object held by a static field stays reachable, a common cause of memory leaks in caches.

See it in the infographic: Frames on the stack, objects on the heap

Does every object created with new end up on the heap?

In the language model, yes. But HotSpot's C2 JIT (just-in-time) compiler runs escape analysis on hot code: an object that never leaves the compiled method, after inlining, can be scalar-replaced, its fields kept in registers or stack slots, so no heap allocation happens at all. It is an optimization of performance, never of behavior, and you see it only in allocation profiles.

  • Escape analysis checks whether an object can be seen outside the method or thread that created it.
  • A non-escaping object can be scalar-replaced, so it is never allocated on the heap.
  • It applies only to JIT-compiled hot code, and the program's results stay the same.
static int sum(int i) {
    Point p = new Point(i, i + 1); // never leaves sum()
    return p.x + p.y;
}
// Once sum() is hot, C2 can remove this allocation.

See it in the infographic: Frames on the stack, objects on the heap

What does a stack frame hold?

The method's local variables, which include its parameters and this for an instance method, an operand stack for intermediate values, and a link to its class's run-time constant pool. javac sizes both arrays: javap -v shows stack=2, locals=2 for static void move(Point q, int x). The frame is discarded when the method returns or throws.

How big is a thread's stack, and can you change it?

Each thread's stack has a fixed maximum size, set for all threads with -Xss, for example -Xss4m. The default depends on the platform. A larger stack lets recursion go deeper before a StackOverflowError: in one run, -Xss4m allowed about ten times as many frames as the default.

Where does a primitive field such as int x in a Point live?

Inside the Point object, on the heap. Only primitive locals and parameters sit in a stack frame. Code reaches p.x through the reference p, so every reference to that Point sees the same x.

Check yourself

1. What does this print?
static void move(Point q, int x) { q.x = x; x = 0; }

int n = 99;
Point p = new Point(1, 2);
move(p, n);
System.out.println(p.x + " " + n);
Show answers
  • 99 99: Correct. q copies the reference, so q.x = x reaches p's Point; x = 0 changes only move's copy of n.
  • 1 99: Incorrect. q points at the same Point as p, so writing q.x changes what p sees.
  • 99 0: Incorrect. x is a copy of n in move's frame; assigning it never touches main's n.
2. swap(Point a, Point b) runs Point t = a; a = b; b = t;. After swap(p, q) returns, which statement is true?
Show answers
  • p and q still point at their original Points: Correct. swap exchanged its own copies of the references; main's p and q were never assigned.
  • p and q now point at each other's Points: Incorrect. That needs pass-by-reference; Java copied the references into a and b.
  • The two Points exchanged their x values: Incorrect. swap never writes a field, so neither object changes.
3. Inside a method, Point p = new Point(1, 2); runs. Where are p and the Point?
Show answers
  • p in the method's stack frame, the Point on the heap: Correct. A local holds only a reference; new creates the object on the heap.
  • Both on the stack, because the method created them: Incorrect. Where an object is created does not move it to the stack; only the reference p is local.
  • Both on the heap: Incorrect. p is a local variable, so it lives in the frame and disappears when the method returns.