Last Updated : 05 Aug, 2025
Java memory management is the process by which the Java Virtual Machine (JVM) automatically handles the allocation and deallocation of memory. It uses a garbage collector to reclaim memory by removing unused objects, eliminating the need for manual memory management
JVM Memory StructureJVM defines various runtime data areas used during the execution of a program. Some of the areas are created by the JVM, whereas some are created by the threads that are used in a program. However, the memory area created by the JVM is destroyed only when the JVM exits. The data areas of a thread are created during instantiation and destroyed when the thread exits. These areas include:
The image below demonstrates the Java Memory Area parts:
jvm-memory 1. Heap AreaScanner sc = new Scanner(System.in)
Here, the Scanner object is stored in the heap and the reference sc is stored in the stack
2. Method AreaNote: Garbage collection in heap area is mandatory.
Note: Method area is logically a part of heap, many JVM like HotSpot uses a separate space known as Metaspace outside the heap to store it.
Example: Java Program to demonstrate how java variables are stored in the different memory areas
Java
import java.io.*;
class Geeks {
// static variables are stored in the Method Area
static int v = 100;
// instance variables are stored in the Heap
int i = 10;
public void Display()
{
// local variables are stored in the Stack
int s = 20;
System.out.println(v);
System.out.println(s);
}
}
public class Main {
public static void main(String[] args) {
Geeks g = new Geeks();
// Calling the Display method
g.Display();
}
}
Note:
3. JVM Stacks
- Static variables are stored in the Method Area.
- Instance variables are stored in the Heap.
- Local Variables are stored Stack.
Heap
Stack
Stores objects and instance variables.
Stores method calls and local variables.
Larger but slower.
Smaller but faster.
Random access.
LIFO (Last-In-First-Out).
Allocation is manual (using 'new' keyword), but deallocation is automatic.
Allocation and deallocation both are automatic.
Long-lived.
Short-lived (method duration).
Shared among all threads (needs synchronization).
Each thread has its own stack (thread safe).
Garbage Collector in javaThe Garbage collector automatically removes the unused objects that are no longer needed. It runs in the background to free up memory.
Note: You can request GC with System.gc() or Runtime.gc(), but JVM decides when it runs.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4