跪拜 Guibai
← Back to the summary

The Anatomy of a JVM Frame: `locals=` vs `stack=` in `javap` Output

Java source code is compiled by javac into a class file, where each method body is a series of bytecode instructions executed one by one by the JVM. In the output of javap -v, every method that has a body (native and abstract methods have none) shows an unremarkable set of numbers ⬇️

  public int add(int, int);
    descriptor: (II)I
    flags: (0x0001) ACC_PUBLIC
    Code:
      stack=2, locals=3, args_size=3
         0: iload_1
         1: iload_2
         2: iadd
         3: ireturn

stack and locals correspond to two sizes from the Frame in section 2.6 "Frames" of the JVM specification. This article uses the four instructions of the add method from Demo.java to explain where they come from.

Frames: Created on Every Call

Section 2.6 of the specification says:

A new frame is created each time a method is invoked.

Every time a method is called, the JVM builds a frame on the current thread's stack; when the method returns, either normally or abnormally, the frame is destroyed. A frame contains three parts:

This article only looks at the first two parts; the third one is related to constant pool resolution and will be covered later.

The size of a frame is determined at compile time ⬇️

The sizes of the local variable array and the operand stack are determined at compile-time and are supplied along with the code for the method...

These two sizes are written in the Code attribute (The Code Attribute, 4.7.3), and javap -v displays them as locals= and stack=.

Example: add from Demo.java

The example code for this article ⬇️ (save it as Demo.java)

public class Demo {
    public static void main(String[] args) {
        SimpleAdder adder = new SimpleAdder();
        int sum = adder.add(1, 2);
        System.out.println(sum);
    }
}

class SimpleAdder {
    public int add(int a, int b) {
        return a + b;
    }
}

Compile Demo.java and inspect the SimpleAdder class with these commands (I'm using JDK 21):

javac -g Demo.java          # -g generates debugging info like LocalVariableTable
javap -v SimpleAdder.class  # add is defined in SimpleAdder, not Demo.class

The add method compiles to only four instructions ⬇️

  public int add(int, int);
    descriptor: (II)I
    flags: (0x0001) ACC_PUBLIC
    Code:
      stack=2, locals=3, args_size=3
         0: iload_1
         1: iload_2
         2: iadd
         3: ireturn
      LineNumberTable:
        line 11: 0
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
            0       4     0  this   LSimpleAdder;
            0       4     1     a   I
            0       4     2     b   I

javap is the JDK's class file disassembler. -v prints all attributes of the class, including the constant pool and constructors; I've only extracted the parts relevant to add. descriptor: (II)I means two int parameters and an int return; flags are the access flags. The Code attribute holds the local variable table size, operand stack size, and bytecode instructions.

The 0, 1, 2, 3 on the far left are byte offsets of the instructions, not instruction numbers. Here all four instructions occupy one byte, so the two happen to match; for a loop like spin, the offsets would skip, which the next article will cover.

Its frame structure ⬇️

add-frame.png

On the left are the three slots corresponding to locals=3, with slot numbers below each cell; on the right are the two slots for stack=2. Just after the method is invoked, parameters are already placed in their slots and the operand stack is empty.

The following screenshots come from the companion AddFrameDemo.java, which lets you step through these four instructions. Blue marks the value written in the current step; an amber border marks the slot read.

Local Variables: An Array Starting at 0

Section 2.6.1 of the specification states what a slot can hold ⬇️

A single local variable can hold a value of type int, float, reference, or returnAddress. A pair of local variables can hold a value of type long or double.

Key points ⬇️

  1. It is an array, indices start at 0.
  2. One slot can hold an int, float, reference, or returnAddress.
  3. long and double take two slots and can only be accessed via the smaller index. In this article a and b are both ints, each taking one slot.

How parameters are placed, from 2.6.1:

On class method invocation, any parameters are passed in consecutive local variables starting from local variable 0. On instance method invocation, local variable 0 is always used to pass a reference to the object on which the instance method is being invoked (this in the Java programming language). Any parameters are subsequently passed in consecutive local variables starting from local variable 1.

Summary:

add is an instance method, so this occupies slot 0, a is slot 1, and b is slot 2. The two parameters are loaded with iload_1 and iload_2, where the numbers directly correspond to the slot numbers.

LocalVariableTable is not a required part of a class file; javac only generates it with -g. Without it locals= still exists, just the variable names are lost.

Operand Stack: LIFO with a Maximum Depth

Section 2.6.2 of the specification defines it as:

Each frame contains a last-in-first-out (LIFO) stack known as its operand stack. The maximum depth of the operand stack of a frame is determined at compile-time...

When a frame is created, its operand stack is empty. Instructions push values from local variables, constant pools, or fields; operations pop them, compute, and push results back. For example, iadd pops two ints, adds them, and pushes back one.

The specification's original text:

At any point in time, an operand stack has an associated depth, where a value of type long or double contributes two units to the depth and a value of any other type contributes one unit.

int counts as one depth (i.e., one slot); long and double count as two. Since add uses only ints, we can compute the stack depth for each instruction ⬇️

Instruction Stack (bottom to top) Depth (number of occupied slots)
iload_1 [a] 1
iload_2 [a, b] 2
iadd [a + b] 1
ireturn [] 0

The maximum depth occurs after iload_2: two ints are on the stack simultaneously, depth 2, exactly matching stack=2.

Walking Through the Four Instructions of add

Step 1 iload_1: push a from slot 1 onto the stack ⬇️

add-step1-iload1.png

The read slot 1 is outlined in amber, and a dashed arrow points to the newly pushed slot. The local variable table doesn't change; stack depth goes from 0 to 1.

Step 2 iload_2: push b from slot 2 ⬇️

add-step2-iload2.png

Now both values are on the stack, depth 2, which is stack=2.

Step 3 iadd: pop two ints, push their sum back ⬇️

add-step3-iadd.png

iadd pops b and a from the top, adds them, and pushes back 3. The stack now holds one value, depth back to 1; the local variable table is unchanged.

After ireturn the method ends, so there is no next instruction to execute. The screenshot shows the state after return: the frame has been popped, the local variable table and operand stack no longer exist, only 3 is returned to Demo.main. ⬇️

add-step4-ireturn.png

Download AddFrameDemo.java and run it (requires JDK 16+; this article uses JDK 21) ⬇️

javac AddFrameDemo.java
java AddFrameDemo

Modify a or b, or click Run to automatically execute all four steps.

Numbers Compared

Number Meaning In add
locals=3 Number of slots in local variable table this 1 + a 1 + b 1
stack=2 Maximum depth of operand stack Two ints after iload_1, iload_2
args_size=3 Number of arguments (not slots) this counts as an argument

args_size and locals have different meanings: add has args_size=3 because instance methods count this as an argument; here two ints each occupy one slot, so locals happens to be 3 as well. If a parameter were long, locals would be greater than args_size.

Summary

  1. Frames are created on every method invocation and contain the local variable table, operand stack, and a constant pool reference.
  2. Local variable table is an array with index starting at 0; instance methods put this in slot 0 and parameters from slot 1; long/double take two slots and are accessed via the smaller index.
  3. Operand stack is LIFO, empty at creation, with a maximum depth given by stack=; long/double count as two depth units, other types as one.
  4. locals= is the number of slots, args_size= is the number of arguments; they mean different things.
  5. LocalVariableTable requires javac -g; it has no effect on locals= itself.

The next article looks at the spin loop from section 3.2: how local variables and the operand stack compile i++ and loop conditions into several instructions.

References