How Java Code Executes – Step by Step Guide with JVM, JRE, and Compilation Explained
Learn exactly how Java code is executed from writing source code to running it on JVM, including compilation, bytecode generation, and execution flow.
How Java Code Executes – Complete Detailed Tutorial
Java code execution is different from traditional compiled languages like C/C++. Java is a platform-independent, interpreted language, which means the code is first compiled into bytecode and then executed by JVM.
Understanding the execution process is crucial for both beginners and advanced Java developers.
1. Steps in Java Code Execution
Java code execution involves three major steps:
- Writing Java Source Code (
.java) - Compilation using JDK (
javac) → Converts code to bytecode (.class) - Execution by JVM (
java) → JVM interprets or JIT compiles bytecode
2. Step 1 – Writing Java Source Code
- Write human-readable code in Java syntax
- File extension:
.java - Example:
- Save file as
Hello.java
Explanation:
Hello→ Class namemain()→ Entry pointSystem.out.println()→ Print output
3. Step 2 – Compilation by JDK
- Use JDK's
javaccompiler to convert.javainto bytecode. - Command:
- Output:
Hello.class(bytecode)
Why Bytecode?
- Bytecode is platform-independent
- JVM on any OS can interpret bytecode
- Enables WORA – Write Once, Run Anywhere
4. Step 3 – Execution by JVM
- JVM loads, verifies, and executes bytecode.
- Command:
- Output:
JVM Execution Flow
- Class Loader: Loads
.classfile - Bytecode Verifier: Ensures bytecode is safe and correct
- Interpreter / JIT Compiler: Executes bytecode as machine code
- Runtime Data Areas: Manages memory (Heap, Stack, Method Area)
- Garbage Collection: Automatically removes unused objects
5. Detailed Diagram of Java Code Execution
6. Compilation vs Interpretation in Java
| FeatureCompilationInterpretation | ||
| Tool | javac | JVM / Interpreter |
| Input | .java file | .class file (bytecode) |
| Output | Bytecode | Machine code execution |
| Speed | Faster (compiled once) | Slower (interpreted line by line) |
| Platform | Platform-independent (bytecode) | Platform-dependent (JVM) |
Key Concept:
Java is both compiled and interpreted, using JIT compiler to speed up execution.
7. Command-Line Example of Execution
- Write code in
Hello.java
- Compile:
- Run:
- Output:
8. Advanced Note: JIT Compilation
- Just-In-Time (JIT) Compiler converts bytecode into native machine code during runtime
- Improves performance
- Frequently executed methods are compiled into machine code
9. Summary
- Java code execution = Source Code → Bytecode → JVM Execution
- Compilation produces platform-independent bytecode
- JVM converts bytecode to machine code
- Ensures security, portability, and performance
Key Points to Remember:
javac→ Compile →.classbytecodejava→ JVM → Execute bytecode- JVM interprets or JIT compiles code
- Platform-independent + secure + robust