Java Bytecode Fundamentals: JVM Opcodes and Class Files
Inspect Java bytecode, understand JVM operand stacks and local slots, and learn what javap reveals about class files, opcodes, and verification.
Inspect Java bytecode, understand JVM operand stacks and local slots, and learn what javap reveals about class files, opcodes, and verification.
Java Bytecode Fundamentals: JVM Opcodes and Class Files
Java compilers write JVM instructions and metadata into .class files. The Java Virtual Machine Specification defines their class-file format and an abstract execution model; it does not require every JVM to translate each instruction into native machine code. Implementations may interpret instructions, compile selected code, or use other execution strategies. HotSpot’s Java SE 27 guide describes its interpreter and tiered compilation, but those are HotSpot implementation details.
This article covers the stack-based instruction model, opcodes, local variable slots, and how to inspect class files with javap. The specification references use the Java SE 27 JVM Specification.
Introduction
The JVM specification describes a stack-oriented instruction model: instructions such as iadd consume values from the operand stack, while load instructions move values from local-variable slots onto that stack. A JVM implementation may represent or execute this model differently internally. Class files are portable across conforming implementations, but bytecode alone does not tell you which runtime strategy ran a method or how fast it was.
When to use bytecode analysis
Inspect bytecode when you want to:
- See which instructions and class-file metadata a compiler emitted.
- Use a profiler to find hot code, then inspect bytecode if it helps explain the result.
- Check what a framework generates for proxies, lambdas, or method references.
- Study class-file and JVM runtime concepts through concrete examples.
- Review compiled artifacts when investigating possible bytecode manipulation.
When not to use bytecode analysis
Direct bytecode inspection is rarely needed for:
- Ordinary application changes, where source code is usually enough.
- The first pass at performance tuning. Profile first, then inspect bytecode if the profile points to a specific method.
- Simple debugging tasks, where logs or a focused test can answer the question.
JVM stack-based architecture
The Java SE 27 JVM Specification defines method frames with a local-variable array and an operand stack. Instructions operate on values in this abstract stack model. The specification describes what these instructions mean; it leaves implementation choices, including internal data structures and machine-code translation, to each JVM.
flowchart TD
subgraph Method["Abstract Method Frame"]
direction TB
LV["Local Variables\n[0] this\n[1] arg1\n[2] arg2\n[n] temp..."]
OS["Operand Stack\npush/pop\niadd, aload, ifeq..."]
end
subgraph JVM["Possible JVM execution strategies"]
direction TB
EXEC["Implementation-specific runtime"]
INT[Interpreter]
JIT[Compiler]
EXEC --> INT
EXEC -.-> JIT
end
LV <--> OS
OS --> EXEC
Reading the stack model
The class file describes operations on abstract values rather than naming processor registers. A conforming JVM maps those operations to its target platform. For example, iadd consumes two integer values from the operand stack and pushes their sum. Verification checks that the instruction uses compatible types and control-flow states; the JVM Specification defines the constraints, while implementations choose how to perform the checks.
Operand stack details
The operand stack follows a last-in, first-out model. Its values have types such as int, float, reference, long, and double. Under the JVM specification, long and double values use two units in the local-variable array and operand stack.
Consider this simple Java method:
public int add(int a, int b) {
return a + b;
}
The bytecode for this method looks like:
iload_1 // Push local variable 1 (a) onto stack
iload_2 // Push local variable 2 (b) onto stack
iadd // Pop two ints, push their sum
ireturn // Return the int on top of stack
The i prefix denotes an integer operation. Other common prefixes are l for long, f for float, d for double, and a for references. Byte, short, char, and boolean values generally use the JVM’s int computational type; baload and bastore are array instructions for byte or boolean arrays.
JVM opcodes: the instruction set
The Java SE 27 JVM Specification describes the class-file format in Chapter 4 and the instruction set in Chapter 6. Each instruction starts with a one-byte opcode and may be followed by operand bytes. Thus, some instructions occupy more than one byte; “bytecode” refers to the byte-encoded instructions stored in a class file.
Instruction categories
| Category | Examples | Purpose |
|---|---|---|
| Load/Store | aload, astore, iload, istore |
Move values between locals and operand stack |
| Arithmetic | iadd, isub, imul, idiv, irem |
Perform calculations on numeric types |
| Type Conversion | i2l, i2f, i2d, l2i |
Cast between primitive types |
| Object Operations | new, getfield, putfield, monitorexit |
Create objects and access fields |
| Control Flow | ifeq, ifne, if_icmpge, goto |
Branch based on stack values |
| Method Invocation | invokevirtual, invokestatic, invokespecial |
Call methods |
| Return | ireturn, areturn, return |
Exit method with or without value |
Quick reference: load and store
Some load and store instructions have short forms that encode local-variable slots 0 through 3 in the opcode itself. The indexed form has a separate slot operand.
iload <n> // Indexed form: load int from local variable n
iload_0 // Short form: load from local variable 0
iload_1 // Short form: load from local variable 1
iload_2 // Short form: load from local variable 2
iload_3 // Short form: load from local variable 3
Equivalent short forms exist for several other load and store instructions. A short form uses fewer bytes than the indexed encoding; the JVM specification does not require a compiler to choose it or promise that it executes faster.
Local variable slots
Each method frame has a local-variable array. Slot 0 holds this for an instance method; parameters follow in order, with long and double using two consecutive slots. Other slots can hold local variables and intermediate values.
The class-file LocalVariableTable attribute is optional debug metadata, not the runtime array itself. When present, javap -l can display its variable names and ranges.
How local-variable slots work
Given this Java method:
public class Calculator {
public long square(int x) {
long result = (long) x * x;
return result;
}
}
The local variable table looks like:
| Slot | Variable | Type |
|---|---|---|
| 0 | this |
Calculator (reference) |
| 1 | x |
int |
| 2 | result |
long (occupies slots 2 and 3) |
The bytecode sequence:
iload_1 // Load x onto stack
i2l // Convert int to long (consumes 1 slot, produces 2)
iload_1 // Load x again
i2l // Convert to long
lmul // Multiply two longs
lstore_2 // Store result into slots 2 and 3
lload_2 // Load result from slots 2 and 3
lreturn // Return it
Long and double values use two slots
A long or double occupies two consecutive local-variable slots. For example, lload_2 loads the long value beginning at slot 2, which occupies slots 2 and 3. The JVM specification does not prescribe how a runtime maps these abstract slots to machine registers.
Two-slot values behave differently on the operand stack too. Take a method that multiplies two longs:
public long multiply(long a, long b) {
return a * b;
}
The bytecode for this method loads each long (occupying two slots), performs the multiplication, and stores the result:
lload_1 // Load a (occupies slots 1 and 2)
lload_3 // Load b (occupies slots 3 and 4)
lmul // Multiply two longs, push result (2 slots)
lreturn // Return long from stack
The local variable table for this method looks like:
| Slot | Variable | Type |
|---|---|---|
| 0 | this |
Reference |
| 1 | a |
long (slots 1+2) |
| 3 | b |
long (slots 3+4) |
A common mistake is treating slot 2 or slot 4 as available for another variable. If you declare a third parameter long c, it starts at slot 5 because slot 4 is part of b.
The operand stack also distinguishes one-unit and two-unit values. dup duplicates a one-unit value; the valid forms of dup2 can duplicate either one two-unit value or two one-unit values. These instructions are specified in JVMS Chapter 6.
Production failure scenarios
Some runtime problems are easier to understand when you know how the class file is structured:
1. Stack Overflow from Deep Recursion
Deep or unbounded recursion can exceed the stack space permitted for a thread and cause StackOverflowError. Stack sizing and growth behavior are JVM-specific; the specification does not prescribe a fixed size.
class RecursiveCalls {
static int recurse() {
return recurse();
}
}
Each call requires a frame in the JVM’s abstract execution model. The number of calls that fit depends on the implementation and the code being executed.
2. Verifier Rejection of Corrupted Class Files
When class-file transformation tools rewrite methods, they must keep instruction offsets, exception tables, constant-pool references, and verification metadata consistent. A malformed class-file structure can cause ClassFormatError; a class that violates verification constraints can cause VerifyError. The exact failure depends on the defect.
Verification checks structural and type constraints. It is not a sandbox for arbitrary code: a valid class can still consume excessive CPU or memory, and the verifier does not replace process isolation when running untrusted plugins.
3. Bytecode Does Not Predict Runtime Compilation
The JVMS defines instruction behavior, not whether or when a particular JVM interprets or compiles a method. For example, Oracle’s Java SE 27 HotSpot VM guide documents interpreter and tiered-compilation behavior for HotSpot. Other JVM implementations and releases can make different choices.
Use javap to inspect class-file instructions. Use a profiler and implementation-specific diagnostics to investigate runtime performance; do not infer native code or speed from the bytecode listing alone.
What bytecode can and cannot tell you
| Bytecode inspection can show | Bytecode alone cannot show |
|---|---|
| Instructions and operands emitted in a class | Whether a method ran in an interpreter or compiler |
| Local slots, stack limits, and debug metadata | The native instructions generated at runtime |
| Control flow and method references | Whether a source-level pattern is faster |
Implementation snippets
Inspect a class with javap
Use javap, the Java class-file disassembler. The commands below list instructions, verbose class-file details, and debug tables:
javap -c com.example.MyClass
javap -c -v com.example.MyClass
javap -c -l -p com.example.MyClass
Example javap output
$ javap -c -v Calculator
public long square(int);
descriptor: (I)J
flags: (0x0001) ACC_PUBLIC
Code:
stack=4, locals=4, args_size=2
0: iload_1
1: i2l
2: iload_1
3: i2l
4: lmul
5: lstore_2
6: lload_2
7: lreturn
This representative output was verified by compiling the shown Calculator class with javac 21.0.13 and inspecting it with javap -c -v. The stack=4 value is the maximum operand-stack size in units; locals=4 accounts for this, x, and the two slots used by result.
Observability checklist
When analyzing bytecode in production or pre-production, check:
- Check that the declared maximum stack size fits the instruction sequence.
- Confirm that locals are initialized before use.
- Review exception-handler ranges and targets.
- See whether the verifier accepts the type and control-flow constraints.
- Check for line-number metadata if stack-trace source locations matter.
Security notes
Bytecode can be inspected and often decompiled, so do not treat compiled classes as a way to hide secrets or implementation details. Decompilers can recover readable code, but the result may not preserve source names or structure.
Obfuscators can rename classes and methods or remove debug information, which may make code harder to read. They do not prevent reverse engineering.
If your application runs untrusted code, use an isolation boundary appropriate to that threat model. The verifier checks class-file and type constraints; it is not a sandbox and does not prevent code from consuming excessive resources.
Common pitfalls and anti-patterns
-
Source and bytecode are not identical. A compiler can reorder instructions, remove dead code, or fold constants.
-
longanddoubleuse two units in local-variable and operand-stack accounting. Forgetting this can lead to incorrect slot indexes ormax_stackcalculations. -
At a branch target, the verifier checks the incoming stack states. Incompatible states fail verification.
-
Only some load and store instructions have
_0through_3forms. Instructions such asiaddoperate on the top values of the operand stack. -
Instance methods have
thisin local slot 0; static methods do not. The verifier also checks that a constructor initializesthisbefore using it as an ordinary reference.
Quick recap checklist
- The JVMS describes a stack-based instruction model; implementation details can vary
- Each instruction begins with a one-byte opcode and may include operand bytes
- The operand stack is LIFO;
longanddoubleuse two units - Instance-method local slots start with
this; static-method slots start with the first parameter - Use
javap -c -vto inspect bytecode of any.classfile - Verification checks class-file and type constraints; it is not a sandbox
- Bytecode can be decompiled, so do not rely on it to protect intellectual property
- Deep or unbounded recursion can cause
StackOverflowError
Interview questions
The JVM instruction set describes operations on an abstract operand stack rather than naming processor registers. That lets the same class-file instructions be implemented on different hardware. The specification defines their behavior; it does not promise that a stack-based instruction is faster or smaller than a particular alternative.
iload <n> carries a local-slot index as an operand; the wide instruction can extend the index encoding when needed. iload_0 through iload_3 encode slots 0 to 3 in the opcode and use fewer bytes. Compilers may emit these short forms, but the JVM specification does not require a compiler choice or promise a runtime speed difference.
The Java SE 27 JVM Specification models long and double as occupying two consecutive local-variable slots and two units on the operand stack. This affects parameter indexes and the max_stack and max_locals values in a method's Code attribute. The specification does not define how a JVM maps those units to physical storage.
Class-file parsing checks structure and constraints, while verification checks that instruction types and control-flow states are valid. A malformed class-file structure can cause ClassFormatError; a class that fails verification can cause VerifyError. The verifier is not a sandbox for running untrusted code.
The constant pool stores values and symbolic references such as class names, method names, and field references. Instructions that need one refer to an entry by index instead of embedding the full name or descriptor. The JVM checks and resolves those references under the class-file, loading, and linking rules.
In an instance method, slot 0 holds this; a static method has no receiver slot. A constructor begins with an uninitialized receiver in the verifier's model, and an initialization call changes that state. The verifier rejects invalid uses of the receiver before initialization. Local-variable slot 0 is still available to a static method's first parameter.
Many JVM instructions consume operands from the operand stack and push results back. For example, iadd consumes two integer values and pushes one result; a prior load instruction can move a local value onto the stack. This describes the class-file execution model. A JVM implementation may use a different internal representation while preserving the specified behavior.
These forms encode a small slot index in the opcode itself, so they take fewer bytes than the indexed form. The Java SE 27 JVM Specification defines both encodings, but it does not require a compiler to select one in every applicable case or claim that the shorter form runs faster.
A StackMapTable attribute records verification types at selected bytecode offsets to help describe valid control-flow states. It does not list every operand-stack slot at every instruction. For class-file versions 50.0 and later, an absent attribute is treated as an implicit empty table; verification still follows the rules for the class-file version and method code.
The JVM specification models a long or double as two units on the operand stack and in local-variable accounting. Stack-manipulation instructions have defined forms for one-unit and two-unit values: for example, a valid dup2 form can duplicate one two-unit value or two one-unit values. The verifier checks that the instruction form matches the types on the stack.
The method's Code attribute declares max_stack, the maximum operand-stack size in units. Verification checks that the instruction sequence fits within that declared limit and that stack types are valid along each control-flow path. For example, iadd requires two integer values; a branch merge with incompatible stack types fails verification.
Arithmetic operations have type-specific opcodes: iadd adds integers, ladd adds longs, and dadd adds doubles. The opcode determines the required operand type; the verifier checks that the stack state is compatible. There is no generic add opcode that selects a type by inspecting values at runtime.
An instruction such as invokevirtual refers to a method entry in the constant pool; the operand shown by javap may look like #42. A malformed index or entry can make the class file invalid, while a well-formed symbolic reference that cannot be resolved can fail during linking. The precise error depends on the problem and the applicable class-file rules.
areturn returns a reference value from a method whose declared return type is a class, interface, or array. The plain return instruction completes a constructor or a method declared with void. Other return types use their corresponding instructions, such as ireturn or lreturn.
A one-byte opcode has 256 possible byte values, though some values are reserved or otherwise not valid as instructions. An instruction may include additional operand bytes; for example, bipush has a signed-byte operand, while iload has a local-slot index. Class-file size also includes metadata and a constant pool, so opcode width alone does not determine how large a class or JAR is.
Class-file parsing checks format constraints such as valid attributes, descriptors, and instruction boundaries. Verification checks whether instructions use compatible types and whether control-flow paths have valid states, including constructor initialization rules. A class-file format error and a verification error describe different kinds of failure; the JVM specification defines the constraints, while implementations choose their internal checking process.
In an instance method, slot 0 is this and parameters follow it; in a static method, the first parameter starts at slot 0. A reference parameter in a static method can therefore be loaded with aload_0; that instruction loads a reference from local slot 0 and does not specifically mean this. During construction, the verifier tracks the uninitialized receiver until an initialization call completes. A long or double parameter uses two consecutive slots.
Load instructions copy values from local-variable slots onto the operand stack before operations use them. For example, iload_1 and iload_2 place two integers on the stack, then iadd consumes them and pushes their sum. Store instructions move results back to local slots when needed. This describes the class-file model; it does not prescribe the JVM's internal storage or performance.
javap -c prints each bytecode instruction with its name and any operands. For example, iload_1 loads local slot 1, bipush 10 pushes the signed-byte value 10, and invokevirtual #12 refers to a method through constant-pool entry 12. The number before each colon is the instruction's byte offset in the code array. In verbose output, stack= and locals= report the method's declared maximum operand-stack size and local-variable count.
At a control-flow merge, the verifier checks that incoming states are compatible with the state required at the target. An integer and a reference cannot be treated as the same stack value, while reference types can be checked against an appropriate common verification type. Exception handlers begin with the exception reference on the operand stack. These checks reject invalid class files before the affected method executes.
Further Reading
- Common Bytecode Instructions: examples of JVM instructions
- Method Invocation Bytecode: how method calls appear in class files
- Java SE 27 JVM Specification: class-file format, execution model, and instruction set
- Java SE 27 HotSpot VM Guide: HotSpot runtime and compiler documentation
- Advanced Java & JVM Internals Roadmap: related learning path
Conclusion
Bytecode shows the instructions and metadata stored in a class file; it does not reveal by itself whether a running method was interpreted or compiled. Use javap -c -v to inspect compiler output, then use profiling tools to investigate runtime behavior. Continue with the Common Bytecode Instructions guide for more examples.
Category
Related Posts
Common Bytecode Instructions
Follow a JDK 21 source-to-bytecode trace, then learn how common JVM instructions use locals, operand stacks, branches, method calls, and returns.
Method Invocation Bytecode
Deep dive into JVM method invocation: invokevirtual, invokestatic, invokespecial, invokeinterface, and invokedynamic explained per the JVM Specification.
JVM Bytecode Verification: Type Checking and Stack Map Frames
A practical guide to JVM bytecode verification by class-file version, including type inference, StackMapTable frames, VerifyError debugging, and verification limits.