Java Bytecode as IR
You'll learn how Java uses stack-based bytecode as an intermediate representation to achieve portability and performance.
What is Java Bytecode?
When you compile a Java program, the compiler doesn't produce machine code for your specific CPU. Instead, it generates Java bytecode—a platform-independent intermediate representation designed to run on the Java Virtual Machine (JVM). This bytecode sits between your high-level Java source code and the low-level machine instructions.
Stack-Based Architecture
Java bytecode operates on a stack-based model. Unlike assembly language that uses registers, bytecode instructions push operands onto a stack, perform operations using those stack values, and push results back. For example, adding two numbers involves: push first number → push second number → execute add instruction (which pops both, adds them, and pushes the result).
Think of it like a cafeteria tray stack: you always work with the top items, and operations naturally flow through this last-in-first-out structure.
Platform Independence
This IR strategy is Java's secret to "write once, run anywhere." The same .class bytecode file runs on Windows, Linux, or macOS—any system with a JVM. The JVM translates bytecode to native machine code at runtime, adapting to the specific hardware.
Just-in-Time Compilation
Modern JVMs use JIT compilation to optimize performance. Frequently executed bytecode (hot spots) gets compiled into native machine code on-the-fly, combining interpretation's flexibility with compilation's speed. The JVM profiles your running program and optimizes the most important parts dynamically.
Key Takeaway: Java bytecode serves as a portable, stack-based intermediate representation that enables platform independence while allowing JIT compilers to deliver near-native performance through runtime optimization.