Skip to lesson

Stack vs Heap and Class Loading

"Explain stack vs heap" and "how does class loading work?" are standard questions for any Java role. The interviewer is checking that you can say where each kind of value lives, tell the two memory errors apart, and describe the loader chain.

JVM memory areas: stack, heap, metaspace, PC register

JVM stack is the memory every thread owns for method calls. Each call adds a frame holding its local variables and parameters, and the frame is removed when the method returns.

The JVM splits memory into areas with different jobs. This program marks, in comments, where a reference, an object, a primitive and a static field each live.

Shared by all threads: the heap (objects and arrays) and Metaspace (class metadata). One set per thread: a JVM stack of frames, a program counter and a native method stack. The JVM also uses native memory outside the heap, for example for the code cache and direct buffers.

Example 1 · Where each value lives, in comments

MemoryAreasDemo.javaJava
class Student {    static String college = "NIT Trichy";     // static field: lives with the class (heap, Java 8+)    String name;    int marks;
    Student(String name, int marks) {        this.name = name;        this.marks = marks;    }}
public class MemoryAreasDemo {    static int addGrace(int m) {        int grace = 5;                        // local primitive: on the stack        return m + grace;    }
    public static void main(String[] args) {        int roll = 21;        Student s = new Student("Asha", 78);  // reference s on the stack, object on the heap        s.marks = addGrace(s.marks);        System.out.println(roll + " " + s.name + " " + s.marks + " " + Student.college);    }}
Output
21 Asha 83 NIT Trichy

What this code does

  • roll, s, m and grace are locals: they live in stack frames and disappear when their method returns. The Student object and its fields live on the heap until no reference points to it.
  • college is static: one copy for the class, stored with the class (in the heap since Java 8), shared by every Student.

Per thread: the stack of frames, the PC register (the instruction being run) and the native method stack. Shared by all threads: the heap (objects and arrays) and the method area, which since Java 8 is metaspace in native memory, replacing PermGen. Static values and the string pool live in the heap.

Stack memory is freed when a method returns; heap memory is freed by the garbage collector. Stack size per thread is set with -Xss; the heap with -Xms (start) and -Xmx (maximum).

Where locals, objects and static fields live: draw it

Heap is the memory area shared by all threads where every object and array lives. The garbage collector frees objects that nothing can reach any more.

A method works on copies of its arguments. This program passes an int and a list: one change stays inside the method, the other is visible to the caller.

Text
STACK (thread main)              HEAP (shared)+--------------------+          +---------------------------+| addGrace: m, grace |          | Student { name -> "Asha", || main: roll = 21    |          |           marks = 83 }     ||       s  ----------+--------> | "Asha" (string pool)       |+--------------------+          | Student.class: college     |                                +---------------------------+
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 2 · Stack copies vs one shared heap object

StackHeapDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class StackHeapDemo {    static void change(int count, List<String> list) {        count = 99;                 // changes only this frame's copy        list.add("added in method"); // changes the shared heap object        list = new ArrayList<>();   // only this frame's reference now points elsewhere        list.add("lost");    }
    public static void main(String[] args) {        int count = 1;        List<String> list = new ArrayList<>();        List<String> alias = list;        change(count, list);        System.out.println("count = " + count);        System.out.println("list  = " + list);        System.out.println("alias sees the same object: " + (alias == list) + " " + alias);    }}
Output
count = 1
list  = [added in method]
alias sees the same object: true [added in method]

What this code does

  • change gets copies of count and of the reference list in its own frame. Setting count = 99 and reassigning list change only those copies.
  • list.add(...) follows the copied reference to the one heap object, so main and alias both see the added item.

A whiteboard answer: draw two boxes. Stack (per thread): a frame for main, with addGrace on top, each with its locals. Heap (shared): the objects, with arrows from the stack references to them. Primitives inside methods are values in the frame; primitives that are fields live inside their object on the heap.

The picture also explains pass by value: a method gets a copy of the reference, so it can change the shared object but not the caller's variable.

Predict the output

Predict stack and heap

Read the code, then pick what it prints.

Round 1 of 2

A method changes a copy of an int and the shared object.

public class Demo {
static void change(int n, StringBuilder sb) {
n = 99;
sb.append("!");
}
public static void main(String[] args) {
int n = 1;
StringBuilder sb = new StringBuilder("hi");
change(n, sb);
System.out.println(n + " " + sb);
}
}

StackOverflowError vs OutOfMemoryError

StackOverflowError is thrown when one thread's stack has no room for another frame, almost always from recursion with no base case. OutOfMemoryError is different: the JVM could not allocate memory.

The two errors have different causes and different fixes. This program triggers both on purpose and shows that both are Errors, not Exceptions.

Example 3 · Triggering StackOverflowError and OutOfMemoryError

MemoryErrorsDemo.javaJava
public class MemoryErrorsDemo {    static int depth = 0;
    static void recurse() {        depth++;        recurse();                               // no base case    }
    public static void main(String[] args) {        try {            recurse();        } catch (StackOverflowError e) {            System.out.println("StackOverflowError: the thread's stack ran out of frames");            System.out.println("depth reached more than 1000: " + (depth > 1000));        }
        try {            long[] huge = new long[Integer.MAX_VALUE - 8];   // about 16 GB            System.out.println(huge.length);        } catch (OutOfMemoryError e) {            System.out.println(e.getClass().getSimpleName() + ": the heap could not fit the object");        }        System.out.println("both are Errors, not Exceptions: "                + (Error.class.isAssignableFrom(StackOverflowError.class)                && Error.class.isAssignableFrom(OutOfMemoryError.class)));    }}
Output
StackOverflowError: the thread's stack ran out of frames
depth reached more than 1000: true
OutOfMemoryError: the heap could not fit the object
both are Errors, not Exceptions: true

What this code does

  • recurse() has no base case, so frames pile up until the thread's stack is full. The exact depth depends on -Xss and the JVM, so the program only checks that it passed 1000.
  • A long array of about two billion elements needs about 16 GB, more than the default heap, so the JVM throws OutOfMemoryError. Both classes extend Error.

OutOfMemoryError usually means Java heap space (too many live objects or a leak), but it also appears as Metaspace (too many classes), GC overhead limit exceeded, or unable to create native thread. Neither is a normal Exception: a program should not try to recover from them.

For a stack overflow, fix the recursion or make it iterative; raising -Xss only hides it. For heap OOM, find the leak with a heap dump, or raise -Xmx if the data really is that big.

Find the bug

Which error is coming?

Click the line that causes the memory error.

factorial(5) crashes with StackOverflowError. Which line is the cause?

Round 1 of 2

Class loaders and the delegation model

Parent delegation is the rule that a class loader first asks its parent to load a class, and loads it itself only if the parent cannot. It keeps core classes such as java.lang.String from being replaced.

Three built-in loaders form a chain. These two programs print which loader loaded each class, then show when a static block runs.

Three class loaders in a chain. The request to load Shop goes up from the application loader to the platform loader and then to the bootstrap loader, and each one asks its parent first. If the parent cannot find the class, the request comes back down and the next loader tries itself.

Example 4 · The three built-in class loaders (Java 9+)

ClassLoaderDemo.javaJava
public class ClassLoaderDemo {    static String nameOf(ClassLoader loader) {        return loader == null ? "bootstrap (null)" : loader.getName();    }
    public static void main(String[] args) {        System.out.println("String         -> " + nameOf(String.class.getClassLoader()));        System.out.println("java.sql.Date  -> " + nameOf(java.sql.Date.class.getClassLoader()));        System.out.println("ClassLoaderDemo -> " + nameOf(ClassLoaderDemo.class.getClassLoader()));
        ClassLoader app = ClassLoaderDemo.class.getClassLoader();        System.out.print("Parent chain: " + nameOf(app));        for (ClassLoader p = app.getParent(); ; p = p.getParent()) {            System.out.print(" -> " + nameOf(p));            if (p == null) break;        }        System.out.println();    }}
Output
String         -> bootstrap (null)
java.sql.Date  -> platform
ClassLoaderDemo -> app
Parent chain: app -> platform -> bootstrap (null)

What this code does

  • String is loaded by the bootstrap loader, which Java shows as null. java.sql.Date comes from the platform loader, and our own class from the application loader app.
  • Walking getParent() shows the delegation chain app → platform → bootstrap: each loader asks its parent first.

Example 5 · Predict the output: when does a static block run?

LazyLoadingDemo.javaJava
class FeeRules {    static {        System.out.println("  FeeRules class initialised (static block)");    }
    static final int LATE_FINE = 500;          // compile-time constant: inlined    static int hostelFee = 60000;
    static int total(int tuition) {        return tuition + hostelFee;    }}
public class LazyLoadingDemo {    public static void main(String[] args) throws Exception {        System.out.println("main started");        System.out.println("constant: " + FeeRules.LATE_FINE + " (no initialisation needed)");        System.out.println("calling a static method:");        System.out.println("total: " + FeeRules.total(90000));        System.out.println("calling again: " + FeeRules.total(80000));
        System.out.println("Class.forName on another class:");        Class.forName("Later");    }}
class Later {    static {        System.out.println("  Later class initialised by Class.forName");    }}
Output
main started
constant: 500 (no initialisation needed)
calling a static method:
  FeeRules class initialised (static block)
total: 150000
calling again: 140000
Class.forName on another class:
  Later class initialised by Class.forName

What this code does

  • Reading FeeRules.LATE_FINE does not initialise the class: a static final compile-time constant is copied into the caller at compile time. The first static method call does, so the static block runs then, exactly once.
  • Class.forName("Later") loads and initialises a class by name, which is how JDBC drivers were registered in older code.

A class loader finds a class's bytecode and turns it into a Class object: bootstrap (core classes, shown as null), platform (other Java SE modules such as java.sql) and application (your classpath). Loading is lazy and has phases: loading, linking (verify, prepare, resolve) and initialisation (static initialisers).

Facts that earn marks:

  • Same class name + different loaders = different classes at runtime.
  • ClassNotFoundException: a class asked for by name (Class.forName) is not found.
  • NoClassDefFoundError: a class present at compile time is missing at runtime.
  • Compile-time constants (static final int X = 500) are inlined and do not trigger initialisation.

Order of execution

Order the delegation

Put the steps of loading java.lang.String in order.

JIT in one line

JIT (Just-In-Time) compiler is the part of the JVM that compiles frequently used bytecode to native machine code while the program runs, so long-running Java code gets close to native speed.

The JVM first interprets bytecode and counts how often each method runs. Hot methods are then compiled to machine code. One-line answer: "javac makes bytecode, and at runtime the JIT compiles the hot parts to machine code."

HotSpot has two JIT compilers, C1 (fast, light optimisation) and C2 (slower, aggressive optimisation), used together in tiered compilation. This is also why benchmarks need a warm-up phase before measuring.

Next step

Check your understanding

12 quick questions