How does Java achieve platform independence through bytecode?
Quick Answer
javac compiles Java source into bytecode — a compact, platform-neutral instruction set stored in .class files. The JVM on each platform interprets or JIT-compiles that bytecode into native machine instructions, so the same bytecode runs unchanged wherever a compatible JVM exists.
Detailed Answer
Compilation in Java happens in two stages:
- Source → bytecode:
javactranslates.javafiles into.classfiles containing JVM bytecode — a stack-based instruction set (iload,invokevirtual,areturn, ...) that is independent of any real CPU architecture. - Bytecode → native code: At run time, the JVM's class loader loads and verifies the bytecode, then the execution engine either interprets it directly or uses the JIT (Just-In-Time) compiler to translate hot code paths into native machine code for the actual CPU.
Because step 1 produces the same bytecode regardless of the target OS/CPU, and step 2 is the JVM's job (one JVM binary per platform), the exact same .class/.jar artifact is portable. The bytecode verifier also checks the code for illegal operations (stack underflow, type violations) before execution, which is why untrusted bytecode can be run relatively safely.
This differs from languages like C that compile straight to machine code — those binaries are tied to a specific OS/architecture and must be recompiled per target.