How Java Works (JVM, JRE, JDK)
Understand the journey from Java source code to running program: the compiler, bytecode, and the Java Virtual Machine.
Overview
Key Points
- β’Source code (.java) β compiler (javac) β bytecode (.class) β JVM β output
- β’Bytecode is platform-independent; the JVM converts it to native machine code at runtime
- β’JDK = JRE + development tools (javac compiler, javadoc, debugger)
- β’JRE = JVM + standard library (enough to run Java, but cannot compile)
- β’JVM = the engine that interprets or JIT-compiles bytecode to native instructions
- β’JIT (Just-In-Time) compilation inside the JVM makes Java run fast by compiling hot code paths to native code
Examples
The Java execution pipeline
Step 1: Write source code
β HelloWorld.java
Step 2: Compile with javac
β javac HelloWorld.java
β produces HelloWorld.class (bytecode)
Step 3: Run with java
β java HelloWorld
β JVM reads HelloWorld.class
β JVM executes bytecode
β Output appears in terminalThe .class file is the portable artifact. You can copy it to any machine with a JVM and run it there.
JDK, JRE, and JVM relationship
βββββββββββββββββββββββββββββββββββ
β JDK β
β βββββββββββββββββββββββββββββ β
β β JRE β β
β β βββββββββββββββββββββββ β β
β β β JVM β β β
β β βββββββββββββββββββββββ β β
β β + Standard Library β β
β βββββββββββββββββββββββββββββ β
β + javac, javadoc, tools β
βββββββββββββββββββββββββββββββββββEvery component is nested. The JVM is the core runtime; the JRE adds the class library; the JDK adds developer tools.
Reading bytecode with javap (disassembler)
// After compiling HelloWorld.java, run:
javap -c HelloWorld
// Output (abbreviated):
// 0: getstatic #2 // Field System.out
// 3: ldc #3 // String "Hello, World!"
// 5: invokevirtual #4 // Method println
// 8: returnjavap lets you inspect the bytecode instructions. This is what the JVM actually executes.
Common Mistakes
- Installing only the JRE thinking you can compile Java - you need the full JDK to run javac
- Confusing "bytecode" with "machine code" - bytecode runs on the JVM, not directly on the CPU
- Forgetting that the .class file name must match the class name exactly, not the .java file name
Note
The JVM also manages memory automatically through garbage collection. You never manually free memory in Java - the JVM detects objects that are no longer needed and reclaims their memory.
Exercises
Write Java code and click Run to execute it instantly. When your output looks correct, mark as done.
Completed: 0 / 4 exercises
Knowledge Check
Question 1 of 4