Module 1: Getting Started with Java
Lesson focusUnderstanding Java Bytecode
A beginner-friendly look at what bytecode is, why it is important, and how to inspect it using the `javap` tool.
What is Bytecode? Bytecode is the intermediate, platform-independent instruction set of the Java Virtual Machine. When you compile a .java file, the javac compiler translates your source code into a .class file containing this bytecode.
Why is it Important? Bytecode is the key to Java's "Write Once, Run Anywhere" principle. Since every JVM on every platform can understand the same bytecode, your compiled .class files can be run on any machine with a compatible JRE, regardless of the underlying hardware or operating system.
Human-Readable vs. Machine-Readable: Your .java file is human-readable. The native code that a CPU understands is machine-readable. Bytecode sits in the middle. It is not as readable as source code, but it is more structured and abstract than native machine code.
Inspecting Bytecode with javap: The JDK includes a tool called the Java Disassembler, javap, which allows you to see the bytecode instructions for a compiled class. This is a great way to understand what the compiler is doing behind the scenes.
Example Walkthrough: Let's take a simple Java class and see its bytecode. First, the Java code:
public class SimpleMath { public int add(int a, int b) { return a + b; } }
After compiling this with javac SimpleMath.java, you can run javap -c SimpleMath to see the disassembled bytecode, which will look something like this:
public int add(int, int); Code: 0: iload_1 // Load integer variable from index 1 (a) 1: iload_2 // Load integer variable from index 2 (b) 2: iadd // Add the top two integers on the stack 3: ireturn // Return the integer result
Mini-Exercise: Create a simple class with a method that subtracts two numbers. Compile it and use javap -c to view the bytecode. See if you can identify the isub instruction for subtraction.
// 1. Save the following as MyProgram.java
public class MyProgram {
public static void main(String[] args) {
int x = 10;
}
}
// 2. Compile it from your terminal
> javac MyProgram.java
// 3. Inspect the bytecode
> javap -c MyProgram