Sub topic 5
Reading bytecode with `javap`
This chapter assumes that you can write and run basic Java programs, understand classes, methods, static members, and exceptions, and use javac and java from the command line. You will use javap to inspect the instructions that the Java compiler stores in a .class file.
Compile a small class
Create a file named MathOps.java:
public class MathOps {
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(add(2, 3));
}
}Compile it:
javac MathOps.javaThe compiler creates MathOps.class. This file contains bytecode, which is the instruction format that the Java Virtual Machine (JVM) executes. The bytecode is not processor-specific machine code. The JVM can interpret it or compile frequently used parts into native machine code.
Display the class's bytecode:
javap -c MathOpsThe important part looks like this:
public static int add(int, int);
Code:
0: iload_0
1: iload_1
2: iadd
3: ireturnThe -c option means “disassemble the code.” It asks javap to print JVM instructions for each method.
Trace the operand stack
JVM bytecode uses an operand stack. Instructions push values onto this stack and remove values from it.
| Instruction | Effect |
|---|---|
| `iload_0` | Push local variable 0, the first `int` argument |
| `iload_1` | Push local variable 1, the second `int` argument |
| `iadd` | Pop two `int` values, add them, and push the result |
| `ireturn` | Pop the result and return it |
For add(2, 3), the execution is:
iload_0 stack: [2]
iload_1 stack: [2, 3]
iadd stack: [5]
ireturn returns 5A method also has local-variable slots. In this static method, slot 0 contains a and slot 1 contains b. Instance methods use slot 0 for this, the object on which the method was called. Some values, such as long and double, occupy two slots.
The numbers at the left are bytecode offsets. They identify instruction positions. They are not source-code line numbers.
Inspect more detail
Use -p to include private members and -v for verbose class-file information:
javap -c -p MathOps
javap -v MathOpsVerbose output includes the class version, access flags, fields, methods, and constant pool. The constant pool stores symbolic information such as method names, class names, and type descriptors. Instructions can refer to these entries instead of storing every name directly.
For example, a method call usually has an instruction such as invokestatic or invokevirtual followed by an index into the constant pool. The JVM resolves that symbolic reference during class linking.
Exercise
Exercise
What does the following sequence do: iload0, iload1, isub, ireturn?
Show answer
It loads two integer locals, subtracts the second from the first, and returns the result.