Skip to lesson

Heap versus stack

Every value in a running Java program sits in one of two places: in a stack frame of the thread that is running, or on the shared heap. The rule that decides it is short, and once you know it you can draw the memory of any program and answer the most common JVM interview question.

Objects and arrays live on the heap, references live in frames

The heap stores all objects and is shared by every thread; each thread's stack stores its method calls with their local variables and references.

Stack memory is a thread's JVM stack: the frames of the calls that are running, holding their parameters and local variables. Heap memory is the one shared area where every object and every array is created, whatever method creates it.

The frame of main on the stack holds marks, an int with the value 85 stored directly, and s, a reference. The reference points to a Student object on the heap. The Student object has a name field that is itself a reference to a String object "Asha" on the heap.

Example 1 · Primitives, references, objects and arrays

WhereItLivesDemo.javaJava
import java.util.Arrays;
class Student {    String name;    int rollNo;
    Student(String name, int rollNo) {        this.name = name;        this.rollNo = rollNo;    }}
public class WhereItLivesDemo {    public static void main(String[] args) {        int year = 2;                               // primitive: the value 2 is in main's frame        Student s1 = new Student("Riya", 101);      // s1 (in the frame) refers to an object on the heap        Student s2 = s1;        int[] marks = {78, 91, 66};                 // arrays are objects: the array is on the heap
        s2.rollNo = 105;        int[] sameMarks = marks;        sameMarks[2] = 70;
        System.out.println("year = " + year);        System.out.println("s1.rollNo = " + s1.rollNo + ", same object? " + (s1 == s2));        System.out.println("marks = " + Arrays.toString(marks) + ", same array? " + (marks == sameMarks));    }}
Output
year = 2
s1.rollNo = 105, same object? true
marks = [78, 91, 70], same array? true

What this code does

  • main's frame holds five local variables: the value 2 and four references. The heap holds one Student and one int[], because s2 and sameMarks copy references, not objects.
  • Changing s2.rollNo and sameMarks[2] changes the shared heap objects, so s1 and marks see the new values and == is true.

A local variable of a primitive type holds its value in the frame. A local variable of a class or array type holds only a reference in the frame; the object it refers to is on the heap. Fields are part of their object, so a field is on the heap even when its type is int.

  • int year = 2; in a method: the 2 is in the frame.
  • Student s1 = new Student(...): s1 (a reference) is in the frame, the Student object is on the heap.
  • int[] marks = {78, 91, 66};: the reference is in the frame, the array object is on the heap.

Lifetime: frames end with the call, objects live while reachable

A frame lives exactly as long as its call. When the method returns, the frame is popped and all its local variables are gone at once, with no cleanup work.

Example 2 · An object outlives the frame that made it

TicketLifetimeDemo.javaJava
import java.util.ArrayList;import java.util.List;
class Ticket {    String pnr;    int seat;
    Ticket(String pnr, int seat) {        this.pnr = pnr;        this.seat = seat;    }}
public class TicketLifetimeDemo {    static List<Ticket> booked = new ArrayList<>();   // a static field keeps objects reachable
    static Ticket makeTicket(int seat) {        String pnr = "PNR" + (4500 + seat);           // locals: gone when this call returns        Ticket t = new Ticket(pnr, seat);             // the object outlives this frame        return t;    }
    public static void main(String[] args) {        Ticket mine = makeTicket(12);        System.out.println("Kept by main:  " + mine.pnr + ", seat " + mine.seat);
        booked.add(makeTicket(33));        System.out.println("Kept by list:  " + booked.get(0).pnr);
        makeTicket(40);        mine = null;        System.out.println("Reachable tickets now: " + booked.size());    }}
Output
Kept by main:  PNR4512, seat 12
Kept by list:  PNR4533
Reachable tickets now: 1

What this code does

  • pnr and t are gone when makeTicket returns, but the Ticket object is not: main keeps a reference to the first one, and the static list keeps the second.
  • The seat 40 ticket is unreachable as soon as its call returns, because nobody stored the reference. After mine = null, the seat 12 ticket is unreachable too. Only the ticket in booked is still reachable.

A heap object has no fixed end. It stays as long as it is reachable: the program can still get to it by following references, starting from local variables in live frames or from static fields. A method can create an object, return the reference and end; the object lives on through the caller's variable. When nothing can reach an object any more, it is garbage. The garbage collector frees that memory later, at a time it chooses. The Garbage Collection Basics module explains how it decides.

Speed and size differences

Stack memory is very cheap to use: the space for a frame is set aside when the call starts and dropped when it returns.

Example 3 · How big is the heap?

HeapSizeDemo.javaJava
public class HeapSizeDemo {    public static void main(String[] args) {        long mb = 1024 * 1024;        Runtime rt = Runtime.getRuntime();
        System.out.println("Max heap (the -Xmx limit): " + rt.maxMemory() / mb + " MB");        System.out.println("Heap committed right now:  " + rt.totalMemory() / mb + " MB");
        int[] admissionNumbers = new int[5_000_000];   // about 20 MB, fits easily on the heap        System.out.println("Array of " + admissionNumbers.length + " ints created on the heap");    }}
Sample output
Max heap (the -Xmx limit): 1882 MB
Heap committed right now:  118 MB
Array of 5000000 ints created on the heap

What this code does

  • This run is from Java 21 on a laptop with about 8 GB of RAM: the default maximum heap is 1882 MB, about a quarter of the RAM. Only 118 MB was committed (actually taken from the operating system) at the start; the heap grows when needed.
  • A 20 MB array fits easily on the heap. A thread's stack is only about 1 MB, so large data must never be planned as stack memory: it always goes in heap objects.

Example 4 · Default heap and stack sizes from the JVM itself

Terminal
java -XX:+PrintFlagsFinal -version | findstr /C:MaxHeapSize /C:ThreadStackSize# macOS or Linux: use grep instead of findstrjava -XX:+PrintFlagsFinal -version | grep -E 'MaxHeapSize|ThreadStackSize'
Sample output
     intx CompilerThreadStackSize                  = 0                                      {pd product} {default}
   size_t MaxHeapSize                              = 1973420032                                {product} {ergonomic}
   size_t SoftMaxHeapSize                          = 1973420032                             {manageable} {ergonomic}
     intx ThreadStackSize                          = 0                                      {pd product} {default}
     intx VMThreadStackSize                        = 0                                      {pd product} {default}

What this code does

  • -XX:+PrintFlagsFinal prints every HotSpot option with its final value. This run is Java 21 on 64-bit Windows: MaxHeapSize is 1973420032 bytes (1882 MB), chosen by ergonomics from the RAM.
  • ThreadStackSize = 0 on Windows means "use the operating system default", which is 1 MB there. On 64-bit Linux the same line shows 1024 (KB).

Heap allocation in HotSpot is also fast, because each thread takes new objects from its own small chunk of the heap (a TLAB, thread-local allocation buffer) by moving a pointer. The real cost of the heap comes later, when the garbage collector has to find and free unused objects.

The bigger difference is size. On HotSpot, each thread's stack is small and fixed: 1 MB by default on 64-bit Windows and Linux, set with -Xss. The heap is large: on Java 17 and 21 its default maximum on most machines is a quarter of the RAM, set with -Xmx.

Java code never chooses where an object goes: new always means the heap. The JIT's escape analysis (Execution Engine module) may remove an allocation it can prove is local, but that is an invisible speed trick, not a rule you can rely on.

Tracing a full program with a memory diagram

A memory diagram shows one moment of a program: the frames on the stack, top first, with their local variables, and the heap objects, with arrows for references. Draw it for one marked line, not for the whole run.

Example 5 · A hostel program to trace

MemoryTraceDemo.javaJava
import java.util.ArrayList;import java.util.List;
class HostelStudent {    String name;    int[] marks;
    HostelStudent(String name, int[] marks) {        this.name = name;        this.marks = marks;    }
    int total() {        int sum = 0;        for (int m : marks) {            sum += m;        }        return sum;            // (*) the memory picture in Example 6 is drawn here    }}
public class MemoryTraceDemo {    static int admitted = 0;
    static HostelStudent admit(String name, int[] marks) {        admitted++;        return new HostelStudent(name, marks);    }
    public static void main(String[] args) {        List<HostelStudent> hostel = new ArrayList<>();        hostel.add(admit("Riya", new int[]{78, 91}));        hostel.add(admit("Kabir", new int[]{65, 70}));
        HostelStudent topper = hostel.get(0);        int best = topper.total();
        System.out.println(topper.name + " total: " + best);        System.out.println("Admitted: " + admitted);        System.out.println("Same object? " + (topper == hostel.get(0)));    }}
Output
Riya total: 169
Admitted: 2
Same object? true

What this code does

  • Three calls happen in main: two admit calls, which have both returned, and total(), which is running at line (*). So at that line only two frames are alive: total and main.
  • topper and the list's first element refer to the same HostelStudent, which is why the last line prints true. Example 6 draws this moment.

Example 6 · The memory diagram at line (*)

Text
Memory at line (*) while total() runs for Riya  (simplified picture)STACK of thread main (top first)          HEAP+-----------------------------+| total()                     ||   this  --------------------+-------> HostelStudent#1|   sum = 169                 |           name  -> "Riya"+-----------------------------+           marks -> int[] {78, 91}| main()                      ||   args   -------------------+-------> String[0]|   hostel -------------------+-------> ArrayList [ ref to #1, ref to #2 ]|   topper -------------------+-------> HostelStudent#1 (the same object)|   best   (not assigned yet) |+-----------------------------+         HostelStudent#2                                          name  -> "Kabir"                                          marks -> int[] {65, 70}Static field admitted = 2 (stored with MemoryTraceDemo's Class object, on the heap)Class data of HostelStudent and MemoryTraceDemo: in Metaspace
In short
Frames alive: total, main.
Heap objects: 2 students, 2 int arrays, 1 ArrayList, 1 String[] (plus the strings).
References to HostelStudent#1: total's this, main's topper, and the list.

What this code does

  • sum is an int, so its value sits in total's frame. this in total is a reference to the same object as topper.
  • The admit frames and their name and marks parameters are already gone, but the objects they created are still on the heap because the list refers to them.

Work in this order: list the frames that are alive at that line, write each local variable inside its frame, draw each object once on the heap, then draw one arrow per reference. Two arrows to the same box mean two references to one object, and that is when == gives true.

Predict the output

Copy, or share?

Read each program and pick what it prints.

Round 1 of 4

Two int variables.

public class Round1 {
public static void main(String[] args) {
int x = 5;
int y = x;
y = 6;
System.out.println(x);
}
}

Interview answer: heap versus stack in four sentences

When an interviewer asks "What is the difference between heap and stack memory?", these four sentences cover it:

  1. Each thread has its own stack, made of one frame per method call, while the heap is one area shared by all threads of the JVM.
  2. Local variables and parameters live in frames, primitives as values and objects as references, while every object and array lives on the heap.
  3. A frame is freed the moment its method returns, while a heap object stays until it is unreachable and the garbage collector reclaims it.
  4. A stack is small (about 1 MB per thread by default on HotSpot) and overflows with StackOverflowError, while the heap is large, set by -Xmx, and runs out with OutOfMemoryError: Java heap space.
Be ready for the follow-ups: "Where are instance fields stored?" (in the object, on the heap) and "Is the stack thread-safe?" (locals are private, but the objects they refer to may be shared).

Next step

Check your understanding

12 quick questions