Skip to lesson

How bytecode works: the operand stack

The JVM runs bytecode on a stack machine: instead of named registers, every method works with a small operand stack. Instructions push values onto it, pop their inputs off it and push their results back.

Each frame has local variables and an operand stack

The operand stack is a last-in, first-out work area inside each frame. Bytecode instructions take their inputs from it and leave their results on it.

Every method call gets a frame on the thread's stack. A frame has two work areas. The local variable array is a row of numbered slots: for a static method the parameters fill slots 0, 1, 2 and so on, then the local variables follow.

Example 1 · Five small methods to disassemble

StackDemo.javaJava
public class StackDemo {    static int add(int a, int b) {        int sum = a + b;        return sum;    }
    static int calc(int a, int b, int c) {        return a + b * c;    }
    static int bigger(int a, int b) {        if (a > b) {            return a;        }        return b;    }
    static int sumBelow(int n) {        int sum = 0;        for (int i = 0; i < n; i++) {            sum += i;        }        return sum;    }
    int bonus(int marks) {        return marks + 5;    }
    public static void main(String[] args) {        System.out.println(add(40, 35));        System.out.println(calc(2, 3, 4));        System.out.println(bigger(72, 88));        System.out.println(sumBelow(5));        System.out.println(new StackDemo().bonus(60));    }}
Output
75
14
88
10
65

What this code does

  • Each method is small on purpose: add uses a local variable, calc mixes + and *, bigger has an if, sumBelow has a loop and bonus is an instance method.
  • sumBelow(5) adds 0 + 1 + 2 + 3 + 4 = 10. The next examples show the bytecode behind each method.

Example 2 · Slots in a static and an instance method

Terminal
javac --release 17 StackDemo.javajavap -c StackDemo
Sample output (javac 21, --release 17; excerpt)
  static int add(int, int);
    Code:
       0: iload_0
       1: iload_1
       2: iadd
       3: istore_2
       4: iload_2
       5: ireturn

  static int calc(int, int, int);
    Code:
       0: iload_0
       1: iload_1
       2: iload_2
       3: imul
       4: iadd
       5: ireturn

  int bonus(int);
    Code:
       0: iload_1
       1: iconst_5
       2: iadd
       3: ireturn

What this code does

  • In static add(int a, int b), a is slot 0 and b is slot 1, and the local sum gets slot 2: iadd leaves a + b on the stack, istore_2 saves it, iload_2 brings it back for ireturn.
  • In the instance method bonus(int marks), marks is slot 1 because slot 0 is this. iconst_5 pushes the constant 5 without touching the constant pool.

For an instance method, slot 0 holds this and the parameters start at slot 1. The operand stack is a small last-in, first-out area for the values an instruction is working on. Its maximum depth is fixed by javac for each method, so the JVM knows the frame size before the method runs.

That is why add below loads iload_0 and iload_1, while the instance method bonus loads its only parameter with iload_1: slot 0 is taken by this.

Load, store and arithmetic instructions

Load instructions copy a local variable onto the stack (iload_1 pushes slot 1). Store instructions pop the top value into a local (istore_2 writes slot 2). Arithmetic instructions pop their two inputs and push the result: iadd, isub, imul, idiv.

Java
static long totalFare(long fare, int seats) {    return fare * seats;}
static double average(double total, int count) {    return total / count;}
static int constants() {    int a = 5;          // iconst_5    int b = 100;        // bipush    int c = 1000;       // sipush    int d = 100000;     // ldc    return a + b + c + d;}
The operand stack while a + b * c runs with a = 2, b = 3, c = 4. iload_0 pushes 2. iload_1 pushes 3. iload_2 pushes 4. imul pops 3 and 4 and pushes 12. iadd pops 12 and 2 and pushes 14.

Example 3 · Typed instructions and constant sizes

Terminal
javac --release 17 TypedOps.javajavap -c TypedOps
Sample output (javac 21, --release 17; excerpt)
  static long totalFare(long, int);
    Code:
       0: lload_0
       1: iload_2
       2: i2l
       3: lmul
       4: lreturn

  static double average(double, int);
    Code:
       0: dload_0
       1: iload_2
       2: i2d
       3: ddiv
       4: dreturn

  static int constants();
    Code:
       0: iconst_5
       1: istore_0
       2: bipush        100
       4: istore_1
       5: sipush        1000
       8: istore_2
       9: ldc           #7                  // int 100000
      11: istore_3
      12: iload_0
      13: iload_1
      14: iadd
      15: iload_2
      16: iadd
      17: iload_3
      18: iadd
      19: ireturn

What this code does

  • totalFare(long fare, int seats): fare fills slots 0 and 1 (a long takes two), so seats is iload_2. i2l widens the int to a long before lmul. The same pattern with i2d and ddiv appears in average.
  • In constants(), 5 uses iconst_5, 100 uses bipush, 1000 uses sipush, and 100000 is too big for a short, so ldc #7 loads it from the constant pool.

ireturn pops the top value and returns it to the caller. The first letter is the type: i for int, l for long, f for float, d for double and a for a reference (an object). So ladd adds two longs and aload_0 pushes a reference. byte, short, char and boolean use the i instructions, because the JVM treats them as ints while computing. A long or double takes two slots.

Constants are pushed in the smallest form that fits: iconst_m1 to iconst_5 for -1 to 5, bipush for a byte (-128 to 127), sipush for a short (-32768 to 32767), and ldc to load anything bigger from the constant pool.

Trace the code

Follow total(2, 3, 4) through its frame

public class StackTrace {
static int total(int a, int b, int c) {
int product = b * c;
int result = a + product;
return result;
}
public static void main(String[] args) {
int r = total(2, 3, 4);
System.out.println("r = " + r);
}
}

Variables

None yet.

Output

(nothing printed yet)

Line 9main calls total(2, 3, 4): a new frame is pushed for total, with an empty operand stack.

Step 1 of 7

Tracing a + b * c step by step

Tracing bytecode means following the local variables and the operand stack one instruction at a time. For calc(2, 3, 4) returning a + b * c, javac emits iload_0, iload_1, iload_2, imul, iadd, ireturn.

calc(2, 3, 4): locals in slots 0-2, operand stack below

Step 1 of 7

Array: 2, 3, 4.
Operand stack(empty)
The frame starts with the arguments in slots 0, 1 and 2: a = 2, b = 3, c = 4. The operand stack is empty.

Example 4 · A tiny stack machine in Java

StackMachineDemo.javaJava
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Deque;import java.util.List;
public class StackMachineDemo {    // Prints the operand stack from bottom to top, like [2, 12]    static String show(Deque<Integer> stack) {        List<Integer> bottomToTop = new ArrayList<>();        stack.descendingIterator().forEachRemaining(bottomToTop::add);        return bottomToTop.toString();    }
    public static void main(String[] args) {        int[] locals = {2, 3, 4};                       // slot 0 = a, 1 = b, 2 = c        String[] code = {"iload_0", "iload_1", "iload_2", "imul", "iadd", "ireturn"};        Deque<Integer> stack = new ArrayDeque<>();
        System.out.println("calc(2, 3, 4): a + b * c");        for (String op : code) {            switch (op) {                case "iload_0" -> stack.push(locals[0]);                case "iload_1" -> stack.push(locals[1]);                case "iload_2" -> stack.push(locals[2]);                case "imul" -> {                    int right = stack.pop();                    int left = stack.pop();                    stack.push(left * right);                }                case "iadd" -> {                    int right = stack.pop();                    int left = stack.pop();                    stack.push(left + right);                }                case "ireturn" -> System.out.println("ireturn  returns " + stack.pop());                default -> throw new IllegalStateException("Unknown opcode " + op);            }            if (!op.equals("ireturn")) {                System.out.printf("%-8s stack %s%n", op, show(stack));            }        }    }}
Output
calc(2, 3, 4): a + b * c
iload_0  stack [2]
iload_1  stack [2, 3]
iload_2  stack [2, 3, 4]
imul     stack [2, 12]
iadd     stack [14]
ireturn  returns 14

What this code does

  • The program runs the six real instructions of calc with an ArrayDeque as the operand stack and an int[] as the local variable array, printing the stack (bottom to top) after each step.
  • imul and iadd pop the right operand first, because it was pushed last. For + and * the order does not matter, but for isub and idiv it does: left - right.

There are no brackets in bytecode. The order of instructions encodes the precedence: javac loads all three values, multiplies the top two (b and c) first, and only then adds a. This is the same idea as postfix notation, a b c * +, from data structures courses.

Branches and loops: if_icmpge and goto

A branch instruction pops values, tests them and jumps to another offset if the test is true. if_icmpge 19 pops two ints and jumps to offset 19 if the first is greater than or equal to the second; otherwise the next instruction runs.

sumBelow(2): slots n, sum, i

Step 1 of 11

Array: 2, -, -.
Operand stack(empty)
Slot 0 holds n = 2. sum (slot 1) and i (slot 2) have no value yet.

Example 5 · An if and a for loop in bytecode

Terminal
javap -c StackDemo
Sample output (javac 21, --release 17; excerpt)
  static int bigger(int, int);
    Code:
       0: iload_0
       1: iload_1
       2: if_icmple     7
       5: iload_0
       6: ireturn
       7: iload_1
       8: ireturn

  static int sumBelow(int);
    Code:
       0: iconst_0
       1: istore_1
       2: iconst_0
       3: istore_2
       4: iload_2
       5: iload_0
       6: if_icmpge     19
       9: iload_1
      10: iload_2
      11: iadd
      12: istore_1
      13: iinc          2, 1
      16: goto          4
      19: iload_1
      20: ireturn

What this code does

  • bigger: the source says if (a > b), the bytecode says if_icmple 7: "if a <= b, jump to offset 7 and return b". Falling through means a > b, so return a runs.
  • sumBelow: offsets 4 to 6 are the loop test, 9 to 12 are sum += i, iinc 2, 1 is i++ and goto 4 jumps back. When i >= n, if_icmpge 19 leaves the loop to return sum.

Its relatives are if_icmplt, if_icmpgt, if_icmple, if_icmpeq and if_icmpne, and ifeq/ifne test a single value against 0. goto always jumps.

javac usually tests the opposite of your condition, because the jump is the way to skip code. if (a > b) return a; becomes if_icmple to jump past return a. A for (int i = 0; i < n; i++) loop becomes: test with if_icmpge (leave when i >= n), body, iinc to add 1 to i in its slot, and goto back to the test.

Why the JVM is called a stack machine

In a stack machine, instructions find their inputs on an operand stack, not in named registers. Your laptop's CPU is a register machine: an x64 add names the registers it uses.

Example 6 · javac records the stack depth and slot count

Terminal
javap -v StackDemo
Sample output (javac 21, --release 17; filtered)
  static int add(int, int);
      stack=2, locals=3, args_size=2
  static int calc(int, int, int);
      stack=3, locals=3, args_size=3
  static int bigger(int, int);
      stack=2, locals=2, args_size=2
  static int sumBelow(int);
      stack=2, locals=3, args_size=1
  int bonus(int);
      stack=2, locals=2, args_size=2

What this code does

  • stack is the deepest the operand stack ever gets in that method; locals is the number of slots. calc needs a stack of 3 because it holds a, b and c at once; add needs only 2 but 3 slots (a, b and sum).
  • The JVM sizes each frame from these numbers before the method runs, and the verifier checks that no instruction ever goes past them.

JVM bytecode never names registers, so it does not depend on how many registers a CPU has. This makes bytecode compact (iadd is one byte, with no operands) and easy to check: the JVM's verifier can prove that every instruction gets the right types and that the stack never overflows. The stack is a model, though, not how the code finally runs. HotSpot's JIT compiler turns hot bytecode into register-based machine code for the real CPU.

Android shows the other choice: its build tools convert Java bytecode into register-based Dalvik bytecode (.dex files) before the app reaches the phone.

Next step

Check your understanding

11 quick questions