Stack and Heap Memory
- While a program runs, the JVM splits its memory into separate areas
- The two you deal with all the time are the stack (method calls and their local variables) and the heap (objects)
- Knowing what lives where explains how references work, why
==compares objects the way it does, and whereStackOverflowErrorandOutOfMemoryErrorcome from

- Each method call (
main(), thenPrint()) has its own frame on the stack, and the newest frame is on top int i = 5is a primitive local, so the value sits right inmain()’s framesandoin both frames are only references. They point to the same"str"literal in the String pool and the same object, both on the heap
Runtime Data Areas
The JVM specification defines these areas:
| Area | Shared or per thread | Holds |
|---|---|---|
| Heap | Shared by all threads | All objects and arrays |
| Method Area | Shared by all threads | Per-class data: class structure, method bytecode, constants |
| JVM Stack | One per thread | One frame per method call that is currently running |
| PC Register | One per thread | Address of the instruction the thread is running |
| Native Method Stack | One per thread | Calls to native (non-Java, e.g. C) code |
The spec only says what each area does, not how to build it. In HotSpot (the usual JVM), the method area is implemented as Metaspace (since Java 8), which uses native memory outside the heap.
Stack
- Each thread has its own stack
- Every method call pushes a new stack frame on top of the stack. A frame holds:
- The method’s local variables, including its parameters
- Working space for evaluating expressions, and what it needs to return to the caller
- When the method returns (normally or by throwing an exception), its frame is popped and its local variables are gone
- Last In, First Out (LIFO): the method on top is always the one that is running
static void first(int x) {
x = x + 5; // changes first's own copy of x, not main's
second(); // pushes second's frame on top of first's
} For example, see this code (StackFrameDemo.java, below). From inside second() the call stack is [second, first, main], and main’s x is still 10 after first changes its own x to 15.
// Shows that every method call gets its own stack frame with its own local variables
import java.util.List;
public class StackFrameDemo {
public static void main(String[] args) {
int x = 10;
System.out.println("main: x = " + x); // main: x = 10
first(x);
System.out.println("main: x = " + x + " (unchanged)"); // main: x = 10 (unchanged)
}
static void first(int x) {
x = x + 5; // changes first's own copy, not main's
System.out.println("first: x = " + x); // first: x = 15
second();
System.out.println("first: second's frame is gone"); // printed after second() returns
}
static void second() {
int y = 99;
System.out.println("second: y = " + y); // second: y = 99
// StackWalker (Java 9+) lists the frames currently on this thread's stack, top first
List<String> callStack = StackWalker.getInstance()
.walk(frames -> frames.map(StackWalker.StackFrame::getMethodName).toList());
System.out.println(callStack); // [second, first, main]
}
}-
The spec allows stacks to be either fixed-size or growable. In HotSpot, each thread’s stack has a fixed maximum size, set when the thread starts. The default depends on the platform and can be changed with
-Xss(for examplejava -Xss4m MyProgram) -
If calls go too deep, there is no room for another frame and the JVM throws
StackOverflowError. The usual cause is recursion with no base case or a wrong one. See this code (StackOverflowDemo.java, below)StackOverflowDemo.java// Shows that recursion without a base case fills the stack and throws StackOverflowError public class StackOverflowDemo { static int depth = 0; static void recurse() { depth++; recurse(); // no base case: every call pushes another frame } public static void main(String[] args) { try { recurse(); } catch (StackOverflowError e) { // The depth is NOT fixed: it changes with the JVM, platform, stack size (-Xss) // and even between runs (e.g. 45444, 44726, 42618 on one machine) System.out.println("StackOverflowError after " + depth + " calls"); } System.out.println("Frames were popped, main still runs"); // Frames were popped, main still runs } }Recursion this deep freezes the browser tab. Run it on your computer with
java StackOverflowDemo.java.Java 21
The depth at which the stack overflows is not fixed. It changes with the JVM, the platform, -Xss, and even from one run to the next.
Heap
- One heap for the whole program, shared by all threads
- Every object and every array is created on the heap (with
new, and also by string literals, autoboxing, etc.) - An object’s instance fields live inside the object, so they are on the heap too, even if they are primitives like
int - You never free heap memory yourself. The Garbage Collector (GC) removes objects that can no longer be reached (see Garbage Collection)
- If the heap is full and the GC can’t free enough space, the JVM throws
OutOfMemoryError(message:Java heap space) - Heap size can be set with
-Xms(starting size) and-Xmx(maximum size)
HotSpot’s garbage collectors are typically generational: new objects go to a “young” area, and objects that survive several collections move to an “old” area. Most objects die young, so the young area is collected often and cheaply.
Primitives vs References
- A variable of a primitive type (
int,double,boolean, …) holds the value itself - A variable of a reference type (any class, interface or array type) holds a reference to an object on the heap, never the object itself
int a = 5;
int b = a; // copies the value 5
b = 7;
System.out.println(a + " " + b); // 5 7
Person p1 = new Person("Asha");
Person p2 = p1; // copies the reference, not the object
p2.name = "Ravi";
System.out.println(p1.name); // Ravi
System.out.println(p1 == p2); // true (same object) STACK (main's frame) HEAP
+--------------------+
| a = 5 |
| b = 7 | +-----------------+
| p1 = (reference) --+--------> | Person |
| p2 = (reference) --+--------> | name = "Ravi" |
+--------------------+ +-----------------+ newalways creates a new object, so two objects with the same content are still different:==on them isfalse==on references checks whether they point to the same object. To compare content, useequals()(see Strings)
For the full example, see this code (HeapReferenceDemo.java, below).
// Shows references on the stack pointing to objects on the heap, and that Java passes references by value
class Person {
String name;
Person(String name) {
this.name = name;
}
}
public class HeapReferenceDemo {
public static void main(String[] args) {
// Primitives: the value itself is copied
int a = 5;
int b = a;
b = 7;
System.out.println(a + " " + b); // 5 7
// References: the reference is copied, both point to the same heap object
Person p1 = new Person("Asha");
Person p2 = p1;
p2.name = "Ravi";
System.out.println(p1.name); // Ravi
System.out.println(p1 == p2); // true (same object)
// A method gets a copy of the reference: it can change the object...
rename(p1);
System.out.println(p1.name); // Meera
// ...but reassigning its copy doesn't affect the caller's variable
replace(p1);
System.out.println(p1.name); // Meera
// Two objects with the same content are still two different objects
Person p3 = new Person("Meera");
System.out.println(p1 == p3); // false
// After this, the "Meera" object is still reachable through p1 and p2
p2 = null;
System.out.println(p1.name); // Meera
}
static void rename(Person p) {
p.name = "Meera";
}
static void replace(Person p) {
p = new Person("Kiran"); // only this method's copy now points to the new object
}
}Where Each Kind of Variable Lives
| Variable | Where it lives |
|---|---|
| Local primitive | The value is in the method’s stack frame |
| Local reference | The reference is in the stack frame; the object is on the heap |
| Parameter | Same as a local variable (it is one) |
| Instance field | Inside its object, on the heap (primitive or not) |
| Array element | Inside the array object, on the heap |
| Static field | One copy per class, not per object (see note) |
“Primitives go on the stack, objects go on the heap” is only half right. A primitive field is part of its object, so it is on the heap. Only local variables and parameters are on the stack.
The spec treats static fields as per-class data (method area). In current HotSpot versions, their values are actually stored with the class’s Class object on the heap. Either way, there is exactly one copy per class.
HotSpot’s JIT compiler can sometimes avoid a heap allocation for an object that never leaves a method (escape analysis). This is an optimisation only; your program always behaves as if every object is on the heap.
Java Is Always Pass-by-Value
- When you call a method, each argument’s value is copied into the new frame’s parameter
- For a primitive, that value is the number itself
- For an object, that value is the reference. So the method gets a copy of the reference, pointing to the same object
static void rename(Person p) {
p.name = "Meera"; // changes the shared object: caller sees it
}
static void replace(Person p) {
p = new Person("Kiran"); // only changes this method's copy of the reference
}
rename(p1);
System.out.println(p1.name); // Meera
replace(p1);
System.out.println(p1.name); // Meera (p1 still points to the old object) Java has no pass-by-reference. A method can change the object a reference points to, but it can never make the caller’s variable point to a different object.
String Pool
- String literals are kept in a String pool so identical literals share one object
- The pool has been on the heap since Java 7
- Details and examples are in the Strings note
Garbage Collection
- The GC starts from GC roots, such as local variables in active stack frames, static fields and running threads, and follows every reference it can reach
- Any object it can’t reach is eligible for garbage collection. Common ways an object becomes unreachable:
- The last reference to it is set to
null - The last reference to it is reassigned to another object
- The method holding the last reference returns, so its frame (and the local variable) is gone
- The last reference to it is set to
- Objects that only refer to each other in a cycle, with nothing else pointing to them, are still collected
- An object being eligible doesn’t mean it is collected right away. When the GC runs is up to the JVM
System.gc()is only a request. The JVM may ignore it
Person p1 = new Person("Asha");
Person p2 = p1;
p2 = null; // the object is still reachable through p1, so not eligible
p1 = null; // no references left: now eligible for GC For collectors, reference types and memory leaks, see Garbage Collection.
Don’t rely on finalize() to clean up. It was deprecated in Java 9 and marked for removal in Java 18. Use try-with-resources for things like files.
Stack vs Heap
| Aspect | Stack | Heap |
|---|---|---|
| Stores | Frames: local variables and parameters | Objects and arrays (with their fields) |
| Owned by | One per thread | Shared by all threads |
| Lifetime | Until the method returns | Until unreachable and collected by the GC |
| Freed by | Automatically, when the frame is popped | The garbage collector |
| Size | Small, limit per thread (-Xss) | Large, can grow up to a limit (-Xmx) |
| Allocation | Very fast (just move the top of the stack) | Fast, but GC adds work later |
| Thread safety | Locals are private to their thread | Shared objects need synchronisation |
| Error when full | StackOverflowError | OutOfMemoryError |
Common Mistakes
- Thinking a method can swap or replace the caller’s objects. It only gets copies of references (see pass-by-value)
- Assuming every
intis on the stack. Fields are inside objects on the heap - Thinking a local reference variable makes the object thread-safe. The reference is private to the thread, but the object it points to may be shared
- Using
==to compare object content. It compares references - Expecting setting a variable to
nullto free memory right away. It only makes the object eligible, and only if no other reference exists - Catching
StackOverflowErrororOutOfMemoryErrorto “fix” them. They areErrors, a sign the program needs to change (base case, smaller data, bigger limits)