← Back to Chapters

Java Runtime Memory Areas

? Java Runtime Memory Areas

? Quick Overview

When a Java program runs, the JVM divides memory into several logical areas. Each area has a specific role in storing class data, objects, variables, and method calls. Understanding these areas is essential for performance tuning, debugging, and memory management.

? Key Concepts

  • Memory is managed by the JVM, not manually by the programmer
  • Some memory areas are shared, others are thread-specific
  • Garbage Collection mainly works in the Heap
  • Stack memory is automatically created and destroyed

? Runtime Memory Areas

  • Method Area
  • Heap Area
  • Stack Area
  • PC Register
  • Native Method Stack

? Theory & Explanation

? Method Area

Stores class-level data such as class metadata, static variables, and method bytecode. It is shared among all threads.

? Heap Area

Stores objects and instance variables. This is the largest memory area and is managed by the Garbage Collector.

? Stack Area

Stores method calls, local variables, and partial results. Each thread has its own stack.

? PC Register

Keeps track of the currently executing instruction for each thread.

⚙️ Native Method Stack

Stores native (non-Java) method information used by JNI.

? Code Example

? View Code Example
// Demonstrates where variables and objects are stored
class MemoryDemo {
static int staticVar = 10;

int instanceVar = 20;

public static void main(String[] args) {
int localVar = 30;
MemoryDemo obj = new MemoryDemo();
obj.show();
}

void show() {
int methodVar = 40;
System.out.println(methodVar);
}
}
Click Next to Start
? Stack Area
 
? Heap Area
? Method Area

? Live Output / Explanation

Explanation

  • staticVar → Method Area
  • instanceVar & object obj → Heap
  • localVar and methodVar → Stack
  • Method calls are pushed and popped from the Stack

✅ Tips & Best Practices

  • Prefer local variables to reduce heap usage
  • Avoid creating unnecessary objects
  • Understand stack vs heap to debug memory leaks
  • Use profiling tools for memory analysis

? Try It Yourself

  • Create multiple objects and observe memory behavior
  • Add static blocks and track Method Area usage
  • Trigger deep recursion to understand StackOverflowError