The Java Virtual Machine (JVM) is an essential Java Runtime Environment (JRE) component. It is responsible for running Java bytecode and converting it into machine code that your computer's processor can understand. When you compile a Java program, it is transformed into bytecode, stored in .class
files, which the JVM then executes.
The JVM divides its memory into different sections, each with a specific purpose. Understanding these areas is crucial for managing memory effectively in Java applications.
Heap Memory:
Definition: The Heap is the region where all Java objects are stored. Whenever you create an object using the new
keyword, the JVM allocates space for this object in the Heap.
Characteristics:
Example:
public class Example {
int data = 50; // Instance variable stored in Heap
public static void main(String[] args) {
Example e1 = new Example(); // e1 points to an object in Heap
}
}
Stack Memory:
Definition: Stack memory is where method calls, local variables, and references to objects in the Heap are stored. Each thread has its own stack memory, and it is used for execution purposes.
Characteristics:
Example:
public void exampleMethod() {
int x = 10; // Local variable stored in Stack
Example e = new Example(); // Reference stored in Stack, object in Heap
}
Metaspace:
<JAVA_HOME>/lib
directory.<JAVA_HOME>/lib/ext
).Garbage Collection (GC) in Java is the process of automatically identifying and removing objects that are no longer in use, freeing up memory and preventing memory leaks.