Stack vs heap
Every Java thread has its own stack holding method calls and local variables. All objects live in one shared heap that the garbage collector manages. Locals hold references; the things they point at are on the heap.
Detailed Explanation
Think of the stack as a stack of index cards. Each method call pushes a card. The card holds that call's local variables, the parameters it received, and a small working area the bytecode uses. When the method returns, the card is thrown away. Nothing has to be cleaned up, because the whole frame disappears at once.
The heap is a single shared pool of memory for objects. new always allocates there. The heap is not tied to any method or thread, so an object can outlive the method that created it and be shared between threads. Nothing frees heap memory by hand. The garbage collector reclaims objects once nothing can reach them.
That gives the rule you need to hold in your head: in Java, every object is on the heap, and only references and primitive locals are on the stack. An int x = 5 inside a method sits directly in the frame. An int[] a = new int[5] puts the array on the heap and keeps a reference to it in the frame. An int field inside an object is on the heap too, because the whole object is.
Heap allocation is much cheaper than people expect. Each thread gets its own slice of the young generation called a TLAB, a thread-local allocation buffer. Allocating means bumping a pointer forward by the object size and returning the old value. No lock, no free list, usually a handful of instructions. Only when the TLAB is full does the thread take a slower path and ask for a fresh one.
The stack has a hard size limit per thread, set with -Xss and typically around 512 KB to 1 MB. Deep or infinite recursion exhausts it and throws StackOverflowError. The heap has its own limit, -Xmx, and exhausting that throws OutOfMemoryError: Java heap space. These are two different resources with two different failure modes, and confusing them sends you tuning the wrong flag.
The costs differ too. Stack memory is free to reclaim and perfectly cache-friendly, but it is small and vanishes on return. Heap memory is flexible and shared, but you pay for it in garbage collection work: marking, copying survivors, and short pauses at safepoints.
Two exceptions to state up front. First, the JIT compiler can delete an allocation entirely when it proves the object never escapes the method, so some "heap" objects never exist at runtime. Second, a virtual thread's stack is not a fixed native stack; it is stored on the heap and grows on demand, which is exactly why you can run a million of them.
Code Examples
public class StackAndHeap {
static int[] makeArray(int n) {
int size = n * 2; // primitive local: lives in this frame
int[] data = new int[size]; // the array object itself lives on the heap
return data; // the frame is discarded, the array survives
}
static int depth(int n) { // deliberately missing a base case
return depth(n + 1);
}
public static void main(String[] args) {
int[] kept = makeArray(4);
System.out.println(kept.length); // prints: 8
try {
depth(0);
} catch (StackOverflowError e) {
// The stack ran out, not the heap. Each call pushed another frame.
System.out.println("stack exhausted"); // prints: stack exhausted
}
}
}# 512 KB of stack per platform thread, 256 MB of heap.
# Lowering -Xss makes the StackOverflowError above arrive sooner;
# lowering -Xmx has no effect on it at all.
java -Xss512k -Xmx256m StackAndHeapCommon Gotchas
Two limits, two errors
`StackOverflowError` means one thread recursed too deep, so raise `-Xss` or rewrite the recursion as a loop. `OutOfMemoryError: Java heap space` means live objects exceeded `-Xmx`. Raising the wrong one changes nothing.
Stack size multiplies by thread count
`-Xss8m` on a server that creates two thousand platform threads reserves 16 GB of native memory outside the heap. The usual symptom is `OutOfMemoryError: unable to create native thread` while the heap looks healthy.
"Small objects go on the stack" is not how HotSpot works
the JIT does not move objects to the stack. It performs scalar replacement, breaking a non-escaping object into plain fields held in registers, so the object is never allocated at all.