Sub topic 5
Reading bytecode with javap
This chapter assumes you can compile and run a class with javac and java. It also assumes you know that the constant pool is a per-class table of names and literals. Here you learn to disassemble a class with javap and trace what its instructions do to the operand stack and local variables.
What javap does
javap is the disassembler that ships with the JDK. It reads a .class file and prints its members and, if you ask, the bytecode of each method. It needs only the compiled class, not the source. That makes it useful for checking what javac actually produced.
The flags you will use most:
| Flag | Effect |
|---|---|
| `-c` | Print the bytecode of each method |
| `-p` | Include private and package-private members (the default shows only public and protected ones) |
| `-s` | Print each member's internal type descriptor |
| `-l` | Print line number and local variable tables |
| `-v` | Verbose: constant pool, flags, stack and locals sizes, and tables |
Start with the class from the topic plan:
public class MathOps {
public static int add(int a, int b) {
return a + b;
}
}javac MathOps.java
javap -c MathOpsCompiled from "MathOps.java"
public class MathOps {
public MathOps();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static int add(int, int);
Code:
0: iload_0
1: iload_1
2: iadd
3: ireturn
}You never wrote a constructor, but javac added a default one. It loads this and calls the superclass constructor Object.<init>. Seeing generated members like this is one reason to read bytecode.
Anatomy of a line
Each line of Code: has three parts.
- The number before the colon is the offset, in bytes, from the start of the method's code.
- The mnemonic, such as
iload_0, names the instruction. - Operands follow the mnemonic. A
#1is an index into the constant pool. The text after//isjavap's own comment showing what that entry resolves to.
Offsets are not consecutive because instructions have different lengths. In add, every instruction is one byte, so the offsets run 0, 1, 2, 3. An instruction that takes a constant pool index uses three bytes: the opcode plus a two-byte index. In the constructor, invokespecial sits at offset 1 and the next instruction is at offset 4.
Decoding the mnemonics
Most mnemonics follow a pattern. The first letter says which type the instruction works on.
| Prefix | Type |
|---|---|
| `i` | `int` (also `boolean`, `byte`, `char`, `short`) |
| `l` | `long` |
| `f` | `float` |
| `d` | `double` |
| `a` | reference |
So iload_0 loads an int from local variable 0, aload_0 loads a reference, and lmul multiplies two long values. The suffix _0 to _3 is a shortcut that bakes the local variable index into the opcode. For higher indexes the instruction takes an operand, as in iload 4.
Constants have their own family. iconst_0 through iconst_5 (and iconst_m1) push small ints. bipush pushes a value from -128 to 127. sipush handles a 16-bit range. Anything else, including strings and large numbers, comes from the constant pool through ldc. So int x = 6; compiles to bipush 6, not iconst_6, because no such instruction exists.
Tracing the operand stack
Each method call gets a frame with an array of local variables and an operand stack. Instructions read values from the stack and push results back. For a static method, the arguments occupy locals 0, 1, 2, and so on, in order. For an instance method, local 0 holds this.
Trace add(2, 3):
iadd pops two ints and pushes their sum. ireturn pops the top value and hands it to the caller. The stack is empty again when the method ends.
A method with a loop
Here is a method with a field read, a local variable, and a loop:
public class Sum {
private int base = 10;
public int total(int n) {
int sum = base;
for (int i = 1; i <= n; i++) {
sum += i;
}
return sum;
}
}javap -c Sum shows this for total. The constructor is omitted.
public int total(int);
Code:
0: aload_0
1: getfield #2 // Field base:I
4: istore_2
5: iconst_1
6: istore_3
7: iload_3
8: iload_1
9: if_icmpgt 22
12: iload_2
13: iload_3
14: iadd
15: istore_2
16: iinc 3, 1
19: goto 7
22: iload_2
23: ireturnThe constant pool index after getfield may differ on your machine. Work through it in four steps.
- Locals. Slot 0 is
this, slot 1 isn, slot 2 issum, and slot 3 isi.javapshows slot numbers, not names, unless you compiled withjavac -gand runjavap -l. - Setup (offsets 0 to 6). Push
this, readbasewithgetfield, and store it insum. Then push 1 and store it ini. - Condition (7 to 9). Push
iandn.if_icmpgt 22pops both and jumps to offset 22 ifi > n. The compiler inverted the source conditioni <= nto exit the loop. - Body and back edge (12 to 19). Compute
sum + iand store it.iinc 3, 1increments local 3 in place with no stack traffic.goto 7jumps back to the condition.
Branch targets are absolute offsets in this method's code, so you can follow the control flow by matching numbers.
Two slots for long and double
A long or double takes two local variable slots and two stack slots. This shifts the numbering of everything after it:
public class Wide {
static long scale(long a, int b) {
return a * b;
}
}static long scale(long, int);
Code:
0: lload_0
1: iload_2
2: i2l
3: lmul
4: lreturnThe parameter a uses slots 0 and 1, so b is in slot 2, not 1. i2l widens the int to a long, because lmul needs two longs. This widening is invisible in the source but obvious in the bytecode.
Looking at the full picture with -v
Add -v to see what surrounds the instructions:
javap -v MathOpsFor add, the relevant part looks like this:
public static int add(int, int);
descriptor: (II)I
flags: (0x0009) ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=2, args_size=2
0: iload_0
1: iload_1
2: iadd
3: ireturn
LineNumberTable:
line 3: 0- The descriptor
(II)Imeans twointparameters and anintresult. stack=2is the maximum operand stack depth the method needs.locals=2is the number of local variable slots.- The
LineNumberTablemaps bytecode offsets to source lines. Stack traces use it.
The header of the -v output also prints the class file's major version and the whole constant pool. That ties this chapter to the earlier ones. For a class compiled with Java 11, you will see major version: 55.
Common mistakes
- Expecting private members.
javap -cwithout-phides private methods, so the code you are looking for seems to be missing. Add-p. - Reading slot numbers as names. Local variable names are absent unless the class was compiled with
-g. Do not assume slot 2 is the second variable you declared. Parameters come first, andlonganddoubletake two slots. - Disassembling stale classes.
javapreads the.classfile on disk, not your latest edit. Recompile before you compare. - Assuming the source runs as written.
javacfolds constants, so2 * 3becomes a single constant push. It also inverts loop conditions and adds default constructors. The bytecode shows what the JVM actually executes.
Exercises
Exercise
Write the bytecode (mnemonics only) you expect for static int f(int a, int b) { return a * b + 1; }.
Show answer
iload0, iload1, imul, iconst_1, iadd, ireturn. The two arguments are pushed and multiplied, the constant 1 is pushed, the two ints on the stack are added, and the result is returned.
Exercise
For the instance method void g(long x, int y), which local variable slots hold this, x, and y?
Show answer
this is in slot 0. The long x uses slots 1 and 2. The int y is in slot 3.
Exercise
In the total method, why does the loop test use if_icmpgt 22 when the source says i <= n?
Show answer
The jump leaves the loop, so the compiler tests the opposite condition. If i > n is true, execution jumps to offset 22 (the code after the loop). Otherwise it falls through into the loop body.