Skip to lesson

Stack frames and local variables

Every method call gets its own small block of memory on the thread's JVM stack, called a stack frame. The frame holds that call's parameters and local variables, and it disappears the moment the call ends. Drawing these frames is the surest way to predict what a program prints.

A new frame for every method call

A stack frame is the memory the JVM sets aside for one method call. It is pushed on the thread's stack when the method is called and popped when the method returns.

A stack frame is the memory the JVM creates for one method call. When a method is called, its frame is pushed on top of the calling thread's JVM stack.

Example 1 · Frames pushed and popped during a fee calculation

FrameLifeDemo.javaJava
public class FrameLifeDemo {    // Counts this class's frames on the stack, minus framesNow() and show() themselves.    static long framesNow() {        return StackWalker.getInstance()                .walk(s -> s.filter(f -> f.getClassName().equals("FrameLifeDemo")).count()) - 2;    }
    static void show(String text) {        System.out.println(text + "   [frames: " + framesNow() + "]");    }
    static int labFee(int months) {        show("    labFee starts");        int fee = months * 3500;        show("    labFee returns " + fee);        return fee;    }
    static int totalFee(int roomRent, int months) {        show("  totalFee starts");        int lab = labFee(months);        show("  totalFee is back, lab = " + lab);        return roomRent + lab;    }
    public static void main(String[] args) {        show("main starts");        int total = totalFee(30000, 10);        show("main is back, total = " + total);    }}
Output
main starts   [frames: 1]
  totalFee starts   [frames: 2]
    labFee starts   [frames: 3]
    labFee returns 35000   [frames: 3]
  totalFee is back, lab = 35000   [frames: 2]
main is back, total = 65000   [frames: 1]

What this code does

  • main calls totalFee, which calls labFee: each call pushes a frame, so the count grows from 1 to 3. When labFee returns, its frame and its local fee are gone, and the count drops back.
  • framesNow() uses StackWalker to count this class's frames and subtracts its own frame and show's frame, so the number is the frames of the fee methods.

When the method returns, or ends by throwing an exception, its frame is popped and everything in it is gone.

The frame on top always belongs to the method running right now. The frames below it belong to methods that are waiting for a call to come back. The last frame pushed is the first one popped, which is why this memory is called a stack.

Order of execution

One method call, step by step

Tap the steps in the order they happen when main calls total(5000, 3).

Inside a frame: local variables, operand stack, return address

Each frame has three parts. The local variable array has numbered slots for the method's parameters and local variables. The operand stack is a small scratch stack for working values: iadd pops two int values and pushes their sum.

Marks.javaJava
public class Marks {    int bonus = 5;
    static int total(int theory, int practical) {        int sum = theory + practical;        return sum;    }
    int withBonus(int marks) {        int result = marks + bonus;        return result;    }}
One stack frame for the call total(5000, 3) has three parts: the local variable slots (fee = 5000, months = 3, sum not set yet), the operand stack holding 5000 and 3, and frame data with the return address. It sits on top of the thread stack, above the frame of main.

Example 2 · The local variable array and operand stack in javap

Text
javap -v Marks        (output trimmed to the two methods)  static int total(int, int);    ...    Code:      stack=2, locals=3, args_size=2         0: iload_0         1: iload_1         2: iadd         3: istore_2         4: iload_2         5: ireturn    ...  int withBonus(int);    ...    Code:      stack=2, locals=3, args_size=2         0: iload_1         1: aload_0         2: getfield      #7                  // Field bonus:I         5: iadd         6: istore_2         7: iload_2         8: ireturn
In short
total:     slots [theory, practical, sum], at most 2 values on the operand stack
withBonus: slots [this, marks, result], at most 2 values on the operand stack

What this code does

  • Real javap -v output for the Marks class above, compiled by JDK 21's javac with --release 17 and trimmed with .... In total, iload_0 and iload_1 push the two parameters, iadd adds them, istore_2 saves the sum in slot 2 and ireturn hands it back.
  • In withBonus, iload_1 reads marks from slot 1 because slot 0 is this. aload_0 pushes this so getfield can read bonus from the object on the heap.

The third part, frame data, links to the class's constant pool and remembers how to go back to the caller, including where the caller continues (often called the return address).

  • javac works out the sizes ahead of time: locals=3 and stack=2 in Example 2 mean 3 slots and at most 2 working values at once.
  • In a static method, the parameters fill slots 0, 1, ...: theory is slot 0, practical is slot 1, sum is slot 2.
  • In an instance method, slot 0 holds this. That is how withBonus reaches the bonus field (aload_0 then getfield).
This is the model from the JVM specification. After the JIT compiles a method, HotSpot may lay the frame out differently, but your program always behaves as this model says.

Primitives store values, references store a way to reach the object

A local variable of a primitive type, such as int, double or boolean, holds the value itself inside the frame. A local variable of a class type holds a reference: a value the JVM uses to find an object on the heap.

Example 3 · Primitive, object and reassigned reference parameters

ValueVsReferenceDemo.javaJava
class Account {    int balance;
    Account(int balance) {        this.balance = balance;    }}
public class ValueVsReferenceDemo {    static void addCashback(int balance) {        balance = balance + 50;          // changes this frame's copy only    }
    static void addCashback(Account account) {        account.balance = account.balance + 50;   // changes the shared object    }
    static void replaceAccount(Account account) {        account = new Account(9999);     // points this frame's copy somewhere else        account.balance = account.balance + 1;    }
    public static void main(String[] args) {        int upiBalance = 1000;        addCashback(upiBalance);        System.out.println("int after addCashback:     " + upiBalance);
        Account wallet = new Account(1000);        addCashback(wallet);        System.out.println("Account after addCashback: " + wallet.balance);
        replaceAccount(wallet);        System.out.println("Account after replace:     " + wallet.balance);    }}
Output
int after addCashback:     1000
Account after addCashback: 1050
Account after replace:     1050

What this code does

  • addCashback(int) adds 50 to its own copy in its own frame. When it returns, that frame is popped and upiBalance in main is still 1000.
  • addCashback(Account) gets a copy of the reference, follows it to the one Account object on the heap and changes its field, so main sees 1050.
  • replaceAccount points its own copy of the reference at a new object. main's wallet still points to the old object, so the balance stays 1050.

The object itself is never inside the frame. Java always passes arguments by value: the caller's value is copied into a slot of the new frame. For an int, the copy is the number. For an object, the copy is the reference, so both frames reach the same object.

  • Change a primitive parameter: only the callee's copy changes.
  • Change a field through a reference parameter: the caller sees it, because there is one object.
  • Point a reference parameter at a new object: only the callee's copy changes; the caller still points to the old object.

Tracing frames during nested calls and recursion

To trace a program, draw one box per frame, newest on top, with its local variables inside. A recursive method works the same way: each call gets its own frame with its own copy of the parameters, so digitSum(4721) and digitSum(472) never share an n.

Example 4 · Tracing a recursive digit sum

DigitSumTraceDemo.javaJava
public class DigitSumTraceDemo {    static int digitSum(int n, int depth) {        String pad = "  ".repeat(depth);        System.out.println(pad + "push digitSum(" + n + ")");
        int result;        if (n < 10) {            result = n;                               // base case: one digit        } else {            result = n % 10 + digitSum(n / 10, depth + 1);        }
        System.out.println(pad + "pop  digitSum(" + n + ") = " + result);        return result;    }
    public static void main(String[] args) {        int rollNumber = 4721;        int sum = digitSum(rollNumber, 0);        System.out.println("Digit sum of " + rollNumber + " is " + sum);    }}
Output
push digitSum(4721)
  push digitSum(472)
    push digitSum(47)
      push digitSum(4)
      pop  digitSum(4) = 4
    pop  digitSum(47) = 11
  pop  digitSum(472) = 13
pop  digitSum(4721) = 14
Digit sum of 4721 is 14

What this code does

  • Each push line is a new frame with its own n, pad and result. The frames are popped in reverse order, and each pop line uses the value returned by the frame above it.
  • At the deepest point there are four digitSum frames on top of main's frame. Example 5 draws that moment.

Example 5 · The stack at the deepest point

Text
JVM stack of thread "main" at the deepest point (top first)(pad and result are left out to keep the picture small)+-----------------------------+| digitSum   n=4     depth=3  |  <- running now+-----------------------------+| digitSum   n=47    depth=2  |  waiting for digitSum(4)+-----------------------------+| digitSum   n=472   depth=1  |  waiting for digitSum(47)+-----------------------------+| digitSum   n=4721  depth=0  |  waiting for digitSum(472)+-----------------------------+| main       rollNumber=4721  |  waiting for digitSum(4721)+-----------------------------+
In short
5 frames at the deepest point, each with its own n.
They are popped in reverse order: n=4, 47, 472, 4721, then main continues.

What this code does

  • This is a hand-drawn picture of the moment digitSum(4) runs in Example 4. Each box is a frame, and each frame holds its own local variables.
  • Nothing in this picture is an object: int values live in the frames themselves. The String that pad refers to is on the heap; the frame only holds the reference.

The deeper the recursion, the more frames sit on the stack at once. A thread's stack has a fixed maximum size, so very deep recursion fills it. The lesson on StackOverflowError and OutOfMemoryError shows what happens then.

Trace the code

Watch frames pile up and disappear

public class FrameTrace {
static int discount(int fee) {
return fee / 10;
}
static int payable(int fee) {
int off = discount(fee);
return fee - off;
}
public static void main(String[] args) {
int fee = 5000;
int due = payable(fee);
System.out.println("Due: " + due);
}
}

Variables

fee
5000

Output

(nothing printed yet)

Line 12Only the frame of main exists. fee holds 5000 inside it.

Step 1 of 8

Next step

Check your understanding

11 quick questions