This content originally appeared on DEV Community and was authored by Tamilselvan K
Memory management is one of the most important concepts in Java. As developers, we often create objects, call methods, and manage data without worrying about where everything is stored. That’s because Java takes care of memory allocation and deallocation using its own memory model and the Garbage Collector (GC).
1. Heap Memory
- It stores Objects, arrays, wrapper class objects, and instance variables.
- Managed by Garbage Collector (GC).
- Heap memory is shared by all threads.
Example:
Student s = new Student(); // Stored in Heap
2. Stack Memory
- Stores Method calls, local variables, and references to objects in the heap.
- Each thread has its own stack.
- Memory is cleared once the method execution is completed.
Example:
public void addNumbers() {
int a = 10; // stored in Stack
int b = 20; // stored in Stack
int sum = a + b; // sum also in Stack
}
3. Method Area
-
It stores Class-level data:
- Static variables
- Class metadata
- Method bytecode
- String Constant Pool (SCP)
Shared by all threads.
Example:
class Test {
static int counter = 0; // stored in Method Area
}
4. Program Counter (PC) Register
- Each thread has its own Program Counter Register.
- It keeps track of the current instruction being executed.
- Helps in switching between threads (multithreading).
5. Native Method Stack
- Used when Java interacts with native code (C/C++).
- Supports execution of native methods through the Java Native Interface (JNI).
This content originally appeared on DEV Community and was authored by Tamilselvan K