Java.Core.What is Heap and Stack memory in Java? What is the difference between them?

Heap and Stack Memory in Java

Java memory is divided into two main areas: Heap Memory and Stack Memory. Each serves different purposes and has distinct characteristics.

1. Heap Memory

  • The heap is the portion of memory where Java objects are stored.
  • It is used for dynamic memory allocation.
  • Objects stored in the heap remain in memory until they are no longer referenced, at which point the Garbage Collector (GC) removes them.
  • All objects and instance variables are stored in the heap.
  • Memory allocation and deallocation are slower compared to the stack.
  • The heap is shared among all threads.

Example of Heap Memory Usage

class Person {
    String name;  // Instance variable (stored in Heap)
    
    Person(String name) {
        this.name = name;
    }
}

public class Main {
    public static void main(String[] args) {
        Person p1 = new Person("Alice");  // 'p1' is stored in Stack, but the object is in Heap
        Person p2 = new Person("Bob");    // Another object in Heap
    }
}
  • The objects "Alice" and "Bob" are stored in heap memory.
  • p1 and p2 are references stored in stack memory.

2. Stack Memory

  • The stack is used for method execution and local variable storage.
  • It follows the LIFO (Last In, First Out) principle.
  • Each thread has its own stack (it is not shared like the heap).
  • When a method is called, a stack frame is created.
  • When a method finishes execution, the stack frame is removed (automatic memory deallocation).
  • It is much faster than heap memory.

Example of Stack Memory Usage

public class Example {
    public static void main(String[] args) {
        int x = 10;  // Local variable (stored in Stack)
        display(x);
    }

    static void display(int num) {
        int y = num * 2;  // 'y' is stored in Stack
        System.out.println(y);
    }
}
  • x and y are stored in stack memory.
  • When display() is called, a new stack frame is created.
  • When display() finishes, its stack frame is removed.

Key Differences Between Heap and Stack

FeatureStack MemoryHeap Memory
Storage TypeStores local variables, method calls, and referencesStores objects and instance variables
Access SpeedFasterSlower
Memory ManagementAutomatic (removed when method exits)Managed by Garbage Collector
Thread ScopeEach thread has its own stackShared among all threads
SizeSmallerLarger
LifetimeExists until method completesExists until Garbage Collector removes unused objects

When to Use Heap vs Stack?

  • Use stack for storing local variables and method calls.
  • Use heap for objects that need to persist beyond a single method execution.
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.