Java Memory Management Explained
Java Memory Management Explained — Heap, Stack, Metaspace + Sample Code
Java Memory Management is the process by which the Java Virtual Machine (JVM) allocates and deallocates memory during program execution. Java automatically manages memory using Garbage Collection (GC), making it safer and easier compared to manual memory management in languages like C or C++.
In Java, memory is mainly divided into:
Heap Memory
Stack Memory
Metaspace
(Plus PC Register & Native Method Stack internally)
Understanding how Heap, Stack, and Metaspace work is critical for:
Writing efficient applications
Avoiding memory leaks
Preventing
OutOfMemoryErrorCracking Java interviews
Heap, Stack, Metaspace
Heap stores objects and instance variables.
Stack stores method calls and local variables.
Metaspace stores class metadata.
Java uses Garbage Collection (GC) to free unused memory.
Poor memory handling can cause memory leaks and performance issues.
Heap stores objects and instance variables.
Stack stores method calls and local variables.
Metaspace stores class metadata.
Java uses Garbage Collection (GC) to free unused memory.
Poor memory handling can cause memory leaks and performance issues.
1. JVM Memory Structure Overview
The JVM memory model is divided into multiple areas. The three most important ones are:
Heap Memory
Stack Memory
Metaspace
Each serves a different purpose.
2. Heap Memory in Java
What is Heap Memory?
Heap Memory is the runtime data area where objects and instance variables are stored. It is shared among all threads.
Whenever you create an object using new, memory is allocated in the heap.
Example: Heap Allocation
class Student {
String name;
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Swathi";
}
}
String name;
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Swathi";
}
}
What Happens Here?
new Student() → Object created in Heap
s1 → Reference variable stored in Stack
"Swathi" → Stored in String Pool (Heap area)
new Student() → Object created in Heap
s1 → Reference variable stored in Stack
"Swathi" → Stored in String Pool (Heap area)
Heap Structure
Heap is divided into:
Young Generation
Old Generation
(Earlier: Permanent Generation, now replaced by Metaspace)
Young Generation
Stores newly created objects.
Old Generation
Stores long-living objects.
Garbage Collector cleans unused objects.
Common Heap Errors
java.lang.OutOfMemoryError: Java heap space
Memory leaks due to unused object references
java.lang.OutOfMemoryError: Java heap space
Memory leaks due to unused object references
3. Stack Memory in Java
What is Stack Memory?
Stack Memory stores:
Local variables
Method calls
Function parameters
Each thread has its own stack.
Stack follows LIFO (Last In, First Out) structure.
Example: Stack Allocation
public class Main {
public static void display() {
int x = 10;
System.out.println(x);
}
public static void main(String[] args) {
display();
}
}
public static void display() {
int x = 10;
System.out.println(x);
}
public static void main(String[] args) {
display();
}
}
What Happens?
main() added to stack
display() added to stack
Local variable x stored in stack
After execution, display() removed
Then main() removed
main() added to stack
display() added to stack
Local variable x stored in stack
After execution, display() removed
Then main() removed
Stack Overflow Error
Occurs when method calls are too deep.
Example (Infinite Recursion):
public class Test {
public static void recursive() {
recursive();
}
public static void main(String[] args) {
recursive();
}
}
This causes:
java.lang.StackOverflowError
Heap vs Stack Comparison
Stores
-
Heap: Objects
-
Stack: Local variables
Heap: Objects
Stack: Local variables
Shared?
-
Heap: Yes
-
Stack: No (Thread-specific)
Heap: Yes
Stack: No (Thread-specific)
Size
-
Heap: Larger
-
Stack: Smaller
Heap: Larger
Stack: Smaller
Memory Management
-
Heap: Garbage Collector
-
Stack: Automatic
Heap: Garbage Collector
Stack: Automatic
Error
-
Heap: OutOfMemoryError
-
Stack: StackOverflowError
Heap: OutOfMemoryError
Stack: StackOverflowError
4. Metaspace in Java
What is Metaspace?
Metaspace stores:
Class metadata
Method metadata
Static variables
Before Java 8, this was called Permanent Generation (PermGen).
From Java 8 onwards, PermGen was removed and replaced with Metaspace.
Why Metaspace Was Introduced?
PermGen had size limitations and often caused:
java.lang.OutOfMemoryError: PermGen space
Metaspace:
Uses native memory
Automatically grows
More flexible
Example: Static Variable in Metaspace
class Demo {
static int count = 0;
}
count stored in Metaspace
Class structure stored in Metaspace
static int count = 0;
}
count stored in Metaspace
Class structure stored in Metaspace
5. How Garbage Collection Works
Garbage Collection (GC) automatically removes unused objects from heap memory.
Java uses algorithms like:
Serial GC
Parallel GC
G1 GC
ZGC (modern low-latency GC)
Example: Garbage Collection
public class GCExample {
public static void main(String[] args) {
String s1 = new String("Java");
s1 = null;
System.gc();
}
}
public static void main(String[] args) {
String s1 = new String("Java");
s1 = null;
System.gc();
}
}
Here:
Object becomes eligible for GC
JVM may clean it
Note: System.gc() is only a request.
6. Memory Leak in Java
Even with GC, memory leaks can happen.
Example:
import java.util.ArrayList;
public class LeakExample {
static ArrayList<String> list = new ArrayList<>();
public static void main(String[] args) {
while (true) {
list.add("Memory Leak");
}
}
}
Here:
Objects are continuously added
Never removed
Heap fills up
Leads to
OutOfMemoryError
7. String Pool in Java
The String Constant Pool is part of heap memory.
Example:
String s1 = "Java";
String s2 = "Java";
Both refer to same object in pool.
But:
String s3 = new String("Java");
Creates new object in heap.
8. Best Practices for Memory Management
✔ Avoid unnecessary object creation
✔ Close resources properly
✔ Use try-with-resources
✔ Monitor memory with profiling tools
✔ Avoid static memory misuse
✔ Understand object lifecycle
9. Tools to Monitor Java Memory
JVisualVM
JConsole
Eclipse MAT
JVM Monitoring Tools
JVisualVM
JConsole
Eclipse MAT
JVM Monitoring Tools
These tools help detect:
Memory leaks
Heap usage
GC activity
10. Interview Questions
What is the difference between Heap and Stack?
What is Metaspace in Java?
What causes StackOverflowError?
What causes OutOfMemoryError?
How does Garbage Collection work?
What is String Pool?
What is the difference between Heap and Stack?
What is Metaspace in Java?
What causes StackOverflowError?
What causes OutOfMemoryError?
How does Garbage Collection work?
What is String Pool?
Real-World Dev Scenario
In large enterprise applications:
Improper heap usage can slow APIs.
Recursive calls can crash systems.
Static misuse can cause memory retention.
Poor GC tuning can affect performance.
Understanding memory structure improves backend performance.
Final Conclusion
Java Memory Management is one of the most important concepts for backend developers. Knowing how Heap, Stack, and Metaspace work helps you:
Optimize performance
Debug memory issues
Avoid runtime errors
Crack Java interviews
Build scalable applications
In 2026, strong knowledge of JVM internals and memory management is essential for:
Java Developers
Backend Engineers
Performance Engineers
Mastering memory management makes you a professional Java developer.
FAQs
1. What is heap memory in Java?
Heap memory stores objects and instance variables created during runtime.
2. What is stack memory in Java?
Stack memory stores method calls and local variables for each thread.
3. What is Metaspace in Java?
Metaspace stores class metadata and static variables in JVM (introduced in Java 8).
4. What causes StackOverflowError in Java?
It occurs due to excessive or infinite method recursion filling the stack.
5. What causes OutOfMemoryError in Java?
It happens when the heap memory is full and garbage collector cannot free space.
6. What is garbage collection in Java?
Garbage Collection (GC) automatically removes unused objects from heap memory.
7. Where are static variables stored in Java?
Static variables are stored in the Metaspace (method area).

Comments
Post a Comment