Bytecode
- Java course
- Expert
- Lesson 3/46
- 5 min
Learn bytecode and instruction inspection with javap.
Bytecode
Bytecode is an intermediate language produced by javac and run by the JVM. Every .class file contains bytecode instructions; they are written for a stack-based machine.
For a method like int add(int a, int b) { return a + b; }, the bytecode uses instructions such as iload, iadd and ireturn. The command javap -c Main.class shows the bytecode instructions.
Bytecode uses a stack machine model: operands are first pushed onto the stack; instructions consume from the stack.
The stack machine model
Bytecode uses the stack machine model. An operation first pushes all its operands onto the stack, then the instruction pops them and pushes the result back.
iload_1 # push a
iload_2 # push b
iadd # pop both, add, push result
ireturn # return the resultThis model produces fewer instructions than register-based machines; instructions are short. The JVM keeps a separate frame for each method call holding this stack structure.
Practice Run a simple method
Define a Main class. Add an int add(int a, int b) method that returns a + b. In main, call add(3, 4) and print the result with System.out.println.
Starter code
public class Main {
// Define a two-parameter int method
public static void main(String[] args) {
// Call the method with 3 and 4 and print
}
}Sample solution
public class Main {
int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
Main m = new Main();
System.out.println(m.add(3, 4));
}
}Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the bytecode instructions
| Term | Meaning |
|---|---|
iload |
Loads a local variable |
iadd |
Adds two ints |
ireturn |
Returns an int |
invokevirtual |
Calls a method |
2 Complete the iadd instruction
iload_1
iload_2
____
ireturn
iload_1
iload_2
iadd
ireturn
Explanation: iadd pops two int values from the stack and adds them.
3 What does javap -c Main.class do?
- Starts the JVM
- Shows bytecode instructions Correct answer
- Deletes the class
- Compiles the source code
Explanation: javap -c lists the bytecode instructions.