← Back to Chapters

Heap vs Stack Memory

? Heap vs Stack Memory

? Quick Overview

In Java, memory is mainly divided into Stack and Heap. Understanding how these two work is critical for performance tuning, debugging memory leaks, and writing efficient Advanced Java applications.

? Key Concepts

  • Stack stores method calls and local variables
  • Heap stores objects and instance variables
  • Stack memory is fast and thread-safe
  • Heap memory is shared and managed by Garbage Collector

? Interactive Simulator

Stack Memory (LIFO)
 
Heap Memory
 
Click buttons to simulate memory allocation...

? Syntax / Theory

  • Stack Memory: LIFO structure, automatic allocation and deallocation
  • Heap Memory: Dynamic allocation, accessed via references
  • Local variables → Stack
  • Objects (new keyword) → Heap

? Code Example – Stack Memory

? View Code Example
// Local variables stored in stack memory
public class StackExample {
public static void main(String[] args) {
int a = 10;
int b = 20;
int sum = a + b;
System.out.println(sum);
}
}

? Code Example – Heap Memory

? View Code Example
// Object created using new keyword is stored in heap memory
class Student {
String name;
int age;
}

public class HeapExample {
public static void main(String[] args) {
Student s1 = new Student();
s1.name = "Ravi";
s1.age = 21;
System.out.println(s1.name);
}
}

? Live Output / Explanation

Explanation

  • a, b, and sum are stored in stack
  • s1 reference is stored in stack
  • Actual Student object is stored in heap
  • Garbage Collector cleans unused heap objects

✅ Tips & Best Practices

  • Prefer local variables to reduce heap usage
  • Avoid creating unnecessary objects
  • Nullify references when objects are no longer needed
  • Understand memory for debugging OutOfMemoryError

? Try It Yourself

  • Create multiple objects and observe memory usage
  • Compare primitive vs object performance
  • Experiment with recursion and stack overflow