Introduction to Java | Programming Basics
What is JVM?
The JVM (Java Virtual Machine) is a virtual machine that runs Java bytecode. It is the cornerstone of Java's platform independence, as it allows Java programs to be executed on any system that has a JVM installed, regardless of the underlying hardware and operating system.
How Does JVM Work?
The JVM performs several key functions:
- Loading Bytecode: It loads compiled Java bytecode from .class files.
- Bytecode Verification: It ensures that the bytecode does not violate Java’s security rules.
- Execution: The JVM interprets the bytecode or uses Just-In-Time (JIT) compilation to convert the bytecode into native machine code for execution.
- Memory Management: The JVM manages memory allocation for objects and performs garbage collection to free unused objects.
JVM Architecture
The architecture of the JVM can be divided into several parts:
- Class Loader Subsystem: Responsible for loading class files.
- Runtime Data Areas: Memory areas used by the JVM to store data during program execution, such as method area, heap, stack, and program counter.
- Execution Engine: Executes the bytecode through either interpretation or JIT compilation.
- Garbage Collector: Automatically manages memory by deleting objects that are no longer in use to reclaim memory.
Components of JVM
Component | Purpose |
---|---|
Class Loader | Loads compiled .class files into memory for execution. |
Runtime Data Areas | Memory spaces used by the JVM for executing the program (e.g., method area, heap, stack). |
Execution Engine | Executes the Java bytecode. It can either interpret or compile the bytecode using the JIT compiler. |
Garbage Collector | Automatically frees memory by cleaning up objects that are no longer needed. |
JVM vs. JRE vs. JDK
To clarify, here’s how JVM differs from JRE and JDK:
- JVM is responsible for running the bytecode.
- JRE includes the JVM and other components to run Java applications (but doesn't have development tools).
- JDK includes the JRE and development tools like the Java compiler for creating Java applications.
Code Example: JVM in Action
When you compile a Java program, it gets converted into bytecode (a .class file) that is executed by the JVM. Below is an example of a simple Java program:
Code Example
public class JVMExample {
public static void main(String[] args) {
System.out.println("This code is being executed by the JVM!");
}
}
Output
This code is being executed by the JVM!
Pro Tip:
💡 Pro Tip
JVM makes Java platform-independent by enabling Java programs to run on any device with the JVM installed, thus adhering to the "Write Once, Run Anywhere" philosophy.