The JVM (Java Virtual Machine) is an essential part of the Java Runtime Environment (JRE) and is responsible for running Java applications. It acts as an interpreter and executor of Java bytecode, making Java programs platform-independent.
How it works
Compilation: When you write a Java program, the source code (in .java files) is first compiled into bytecode by the Java compiler. The bytecode is stored in .class files.
Execution: The JVM reads the bytecode and translates it into machine code that the operating system can understand, enabling the program to run on any device that has a JVM installed. This allows Java to be "write once, run anywhere."
Image is from : javatpoint.com
Key functions
Loading: It loads class files into memory. (Classloader)
Verification: It verifies that the bytecode is valid and doesn't compromise the system.
Execution: It executes the bytecode using either an interpreter or Just-In-Time (JIT) compilation to improve performance.
Garbage Collection: It automatically manages memory by reclaiming memory that is no longer in use.
Stack Memory and Heap Space
Stack is for fast, temporary storage (local variables, method calls).
Heap is for dynamic, longer-term storage (objects and arrays).
Parameter | Stack Memory | Heap Space |
Purpose | Stores method calls, local variables | Stores objects and dynamic data |
Size | Smaller, fixed size | Larger, dynamic size |
Speed | Very fast (LIFO structure) | Slower due to garbage collection overhead |
Lifetime | Memory is freed automatically when a function ends | Memory is freed by garbage collector when no longer referenced |
Access | LIFO (Last In, First Out) | Random access |
Comments