CoursesJVM internals for Kotlin and Android developers
Puzzle 1 · 2 of 5
What does a method receive?
Track one number across a call and back.
All puzzles in this course
The problem
Look at the increment instructions in the class file from the previous puzzle. The caller holds seven. A helper adds one and returns eight. Where did the seven go while the helper ran?
See it
Scroll sideways to see the full diagram.
The called method receives a copy of seven.
Step 1 of 4The load and constant instructions supply two inputs.
Step 2 of 4Addition replaces both inputs with one result.
Step 3 of 4The result returns to the caller.
Step 4 of 4
The building block
A stack frame belongs to one method call. It holds local variables and an operand stack for intermediate values. Calling increment copies the integer argument into its local slot. Inspect increment with javap. The load instruction pushes seven. The next instruction pushes one. Addition consumes both values and pushes eight. The integer return sends eight to the caller and the helper frame is discarded. The original local in the caller still holds seven.
A local is a slot belonging to the current call. The operand stack is its scratch space. In the table the rightmost number is the top, where an instruction takes its next input. The caller passes seven to a static helper, so the helper's first local slot starts at seven.
| Helper instruction | Action | Helper stack afterwards |
|---|---|---|
| Before the first instruction | Receive seven in local slot zero | empty |
| iload_0 | Copy the value in slot zero onto the stack | 7 |
| iconst_1 | Push a constant one | 7, 1 |
| iadd | Remove the two numbers and push their sum | 8 |
| ireturn | Deliver eight to the caller and finish this call | frame discarded |
Notice that loading a local copies its value. If the caller throws away the returned eight and calls the helper again with its original seven, it gets eight again. If it passes the returned eight as the next argument, it gets nine. Trace both paths by drawing a fresh row for each call. This is the execution model described by the instructions. A runtime may optimize how it implements that model.
Try it
Optional local lab
Complete experiment 2 in the JVM source files. Record your prediction before running the program.
Check yourself
Sources
- JVM specification, frames — “A new frame is created each time a method is invoked.”
- Java 21 disassembler guide
What you now know
Each method invocation has its own frame with locals and an operand stack.
Answer every question above correctly to unlock the next puzzle.
Something wrong or unclear on this page? Tell me: a puzzle that didn't click is a bug in the puzzle.