1. What is Memory Management in Java?
- Java manages memory automatically (unlike C where you manually allocate/deallocate).
- The JVM (Java Virtual Machine) is responsible for memory allocation and garbage collection.
- Goal: Efficient use of memory, avoid memory leaks, and improve performance.
2. Memory Areas in JVM
Java memory is divided into several regions:
1. Method Area (a.k.a. Class Area)
- Stores class-level data (class structures, static variables, method code, runtime constants).
- Shared among all threads.
2. Heap Area
- Stores objects and instance variables.
- Managed by Garbage Collector (GC).
- Biggest memory space in JVM.
Subdivisions (Generational Heap):
- Young Generation: Newly created objects (divided into Eden + Survivor spaces).
- Old Generation (Tenured Space): Long-lived objects.
- Permanent Generation (PermGen) – till Java 7 (now replaced with Metaspace in Java 8+).
3. Stack Area
- Stores method calls, local variables, and references to objects.
- Each thread has its own stack (LIFO).
- Stack frames = created for each method call → destroyed after execution.
4. PC Register (Program Counter)
- Stores the address of the currently executing JVM instruction.
5. Native Method Stacks
- Stores native (C/C++) code references if Java calls non-Java libraries.
3. Memory Allocation in Java
- Stack: Local variables, references, method calls.
- Heap: Objects created using
new. - Static: Stored in the Method Area, shared by all objects.
👉 Example:
public class MemoryDemo {
int x = 10; // Stored in Heap (as instance variable)
static int y = 20; // Stored in Method Area (class-level)
public static void main(String[] args) {
int z = 30; // Stored in Stack (local variable)
MemoryDemo obj = new MemoryDemo(); // Reference in Stack, object in Heap
}
}
4. Garbage Collection in Java
What is Garbage Collection?
- Automatic process of removing unused objects from memory (Heap).
- Helps avoid memory leaks.
- Runs in the background using the Garbage Collector (GC) thread.
When does an object become eligible for GC?
-
When reference is set to
null.obj = null; -
When reference goes out of scope.
void test() { MemoryDemo obj = new MemoryDemo(); // eligible after method ends } -
When object is reassigned.
obj1 = new MemoryDemo(); // old object eligible if no other ref exists
Forcing Garbage Collection (not recommended):
System.gc(); // Suggests JVM to run GC
Runtime.getRuntime().gc(); // Alternative
⚠️ Note: JVM is not guaranteed to run GC immediately.
5. Finalization (finalize() method)
- Called by GC before destroying an object.
- Can be overridden but deprecated in Java 9+.
- Example:
@Override
protected void finalize() {
System.out.println("Object destroyed");
}
⚠️ Rarely used in modern Java. Instead, use try-with-resources or AutoCloseable.
6. Common Interview Questions
- Where are Strings stored in Java?
- In String Pool inside Heap → ensures memory efficiency via interning
Difference between Stack and Heap memory?
- Stack → stores local variables, method calls, faster, thread-specific.
- Heap → stores objects, shared across threads, managed by GC.
What is memory leak in Java?
- When objects are no longer used but still referenced → prevents GC from cleaning them.
- Example: Static collections holding unused objects.
- What is Metaspace (Java 8)?
- Replaced PermGen → stores class metadata, grows dynamically with system memory.
- Can we call GC explicitly?
- We can request using
System.gc(), but JVM decides when to run.
7. Best Practices for Memory Management
- Use local variables instead of global when possible.
- Release resources using try-with-resources (
AutoCloseable). - Avoid unnecessary object creation (e.g., reuse immutable objects like Strings).
- Be careful with static variables/collections → can cause memory leaks.
- Use profilers/tools: VisualVM, JConsole, Eclipse MAT to monitor memory.
8. Diagram: JVM Memory Model (Simplified)
+-------------------+ +----------------------+
| Method Area | | Heap (Young+Old) |
| (Class metadata, | | -> Objects |
| static vars) | | -> String Pool |
+-------------------+ +----------------------+
| Stack (per thr) | | Garbage Collector |
| -> method calls | +----------------------+
| -> local vars |
+-------------------+
| PC Register |
+-------------------+
| Native Method Stk |
+-------------------+
With this chapter, you now fully understand Java Memory Model + Garbage Collection from both a coding & interview perspective.
Next: Chapter 15: File Handling in Java (I/O Streams, Reader/Writer, Serialization)