How bytecode works: the operand stack
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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)); }}75 14 88 10 65
What this code does
- Each method is small on purpose:
adduses a local variable,calcmixes+and*,biggerhas anif,sumBelowhas a loop andbonusis 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
javac --release 17 StackDemo.javajavap -c StackDemo 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: ireturnWhat this code does
- In static
add(int a, int b),ais slot 0 andbis slot 1, and the localsumgets slot 2:iaddleaves a + b on the stack,istore_2saves it,iload_2brings it back forireturn. - In the instance method
bonus(int marks),marksis slot 1 because slot 0 isthis.iconst_5pushes 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.
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;}Example 3 · Typed instructions and constant sizes
javac --release 17 TypedOps.javajavap -c TypedOps 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: ireturnWhat this code does
totalFare(long fare, int seats):farefills slots 0 and 1 (a long takes two), soseatsisiload_2.i2lwidens the int to a long beforelmul. The same pattern withi2dandddivappears inaverage.- In
constants(), 5 usesiconst_5, 100 usesbipush, 1000 usessipush, and 100000 is too big for a short, soldc #7loads 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
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.
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
Example 4 · A tiny stack machine in Java
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)); } } }}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
calcwith anArrayDequeas the operand stack and anint[]as the local variable array, printing the stack (bottom to top) after each step. imulandiaddpop the right operand first, because it was pushed last. For+and*the order does not matter, but forisubandidivit 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
Example 5 · An if and a for loop in bytecode
javap -c StackDemo 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: ireturnWhat this code does
bigger: the source saysif (a > b), the bytecode saysif_icmple 7: "if a <= b, jump to offset 7 and return b". Falling through means a > b, soreturn aruns.sumBelow: offsets 4 to 6 are the loop test, 9 to 12 aresum += i,iinc 2, 1isi++andgoto 4jumps back. Wheni >= n,if_icmpge 19leaves the loop toreturn 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
javap -v StackDemo 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=2What this code does
stackis the deepest the operand stack ever gets in that method;localsis the number of slots.calcneeds a stack of 3 because it holds a, b and c at once;addneeds 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