Stack frames and local variables
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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); }}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
maincallstotalFee, which callslabFee: each call pushes a frame, so the count grows from 1 to 3. WhenlabFeereturns, its frame and its localfeeare gone, and the count drops back.framesNow()usesStackWalkerto count this class's frames and subtracts its own frame andshow'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.
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; }}Example 2 · The local variable array and operand stack in javap
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: ireturntotal: 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 -voutput for theMarksclass above, compiled by JDK 21's javac with--release 17and trimmed with.... Intotal,iload_0andiload_1push the two parameters,iaddadds them,istore_2saves the sum in slot 2 andireturnhands it back. - In
withBonus,iload_1readsmarksfrom slot 1 because slot 0 isthis.aload_0pushesthissogetfieldcan readbonusfrom 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=3andstack=2in Example 2 mean 3 slots and at most 2 working values at once. - In a static method, the parameters fill slots 0, 1, ...:
theoryis slot 0,practicalis slot 1,sumis slot 2. - In an instance method, slot 0 holds
this. That is howwithBonusreaches thebonusfield (aload_0thengetfield).
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
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); }}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 andupiBalanceinmainis still 1000.addCashback(Account)gets a copy of the reference, follows it to the oneAccountobject on the heap and changes its field, somainsees 1050.replaceAccountpoints its own copy of the reference at a new object.main'swalletstill 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
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); }}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 14What this code does
- Each
pushline is a new frame with its ownn,padandresult. The frames are popped in reverse order, and eachpopline uses the value returned by the frame above it. - At the deepest point there are four
digitSumframes on top ofmain's frame. Example 5 draws that moment.
Example 5 · The stack at the deepest point
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)+-----------------------------+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:
intvalues live in the frames themselves. TheStringthatpadrefers 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
Variables
- fee
- 5000
Output
(nothing printed yet)Line 12Only the frame of main exists. fee holds 5000 inside it.
Next step
Check your understanding
11 quick questions