Back to course

Understanding Compilation and the JVM (Java Virtual Machine)

Java Mastery: From Zero to Professional Developer (50-Lesson Journey)

Lesson 4: Understanding Compilation and the JVM

Java's architecture is unique because it uses an intermediary step (bytecode) to achieve platform independence.

The Java Execution Process

The process involves two main steps:

  1. Compilation (using javac): The Java compiler takes your human-readable source code (.java file) and translates it into platform-independent bytecode (.class file).
  2. Interpretation/Execution (using java and the JVM): The JVM reads the bytecode (.class file) and executes it on the host machine's specific operating system.

mermaid sequenceDiagram participant Developer participant SourceCode participant Compiler participant ByteCode participant JVM participant OS

Developer->>SourceCode: Write HelloWorld.java
SourceCode->>Compiler: Input .java file
Compiler->>ByteCode: Output .class file (Bytecode)
ByteCode->>JVM: Load and verify bytecode
JVM->>OS: Execute instructions
OS->>Developer: Display "Hello, World!"

What is Bytecode?

Bytecode is a set of instructions that looks like machine code but is designed to be understood by the JVM, not by a specific hardware CPU. This is the key to Java's "Write once, run anywhere" capability.

JIT Compiler

Modern JVMs use a Just-In-Time (JIT) Compiler. The JIT compiler monitors the running program and identifies frequently used pieces of bytecode. It then compiles these hot spots into native machine code during runtime. This significantly speeds up execution, making Java perform almost as fast as natively compiled languages.