The Byte-Level Anatomy of JVM Instructions: Opcodes, Operands, and Constant Pool References
For anyone writing JVM tools, debugging performance, or generating bytecode, knowing the exact byte layout of instructions is foundational. It clarifies why constants are handled differently based on width rather than type, and how the interpreter's efficiency depends on a compact, predictable encoding.
Every JVM instruction starts with a one-byte opcode, optionally followed by operands. The interpreter loop fetches the opcode, fetches operands if any, executes, and advances the program counter. The design choice of a single-byte opcode caps the instruction set at 256 entries, and forces a tradeoff: many instructions encode extra information (like local variable slots) directly into the opcode, while others rely on operand bytes that must be assembled at runtime.
Concrete examples illustrate the forms: iadd has no operands; bipush carries a 1-byte signed immediate; sipush carries a 2-byte big-endian immediate; iinc takes two operands (a slot index and a signed byte constant); and ldc references a constant pool entry by a 1-byte index. Larger constants, like 1000000, exceed the immediate ranges and must live in the constant pool, accessed via ldc (1-byte index) or ldc_w (2-byte index). long and double values, which occupy two slots, are always fetched with ldc2_w, which has no non-wide variant.
The article also explains the difference between 100 and 1000000: they are both ints, but their widths differ. It includes a Swing-based demo that visualizes the byte stream, operand stack, and local variables step by step, and provides instructions to reproduce the byte dumps using javap and xxd.
The one-byte opcode constraint is a fundamental design decision that trades instruction set size for compactness; it leads to duplicated instruction forms (iload_1 vs iload) and pushes large constants out of the instruction stream.
The distinction between 100 and 1000000 shows that the JVM's encoding is tuned for common small values; this has implications for code generators that want to minimize class file size.
The fact that ldc2_w has no non-wide variant suggests that long and double constants are rare enough in typical code to justify always using a wider index, simplifying the interpreter's logic.