Understanding Heap and Stack Memory in Java

In this article, you will learn about Heap Memory and Stack Memory in Java, which are important for how Java stores and manages data. Java uses Stack Memory to store method calls and temporary variables, while Heap Memory is used for storing objects and data that need longer stays. Understanding these helps you write better programs and avoid errors like running out of memory. By the end of this article, you'll have a clear idea of how Java manages memory and how to use it wisely in your programs.

What is Stack Memory?

Stack Memory is a small, fast memory area that stores method execution details, local variables, and function calls. Each time a method is called, a new block (stack frame) is added to the stack. When the method execution finishes, the block is removed. The stack follows the Last In, First Out (LIFO) principle, meaning the most recent method call is removed first.

Let's take a closer look at how stack memory works through an example.

public class StackExample {
    public static void main(String[] args) {
        int num = 10; // Stored in Stack
        display(num);
    }

    public static void display(int value) {
        System.out.println("Value: " + value);
    }
}

In this example, the variable num is stored in stack memory. When display(num) is called, a new stack frame is created to store the parameter value. Once display() finishes executing, its stack frame is removed, freeing up memory.

What is Heap Memory?

Heap Memory is a larger memory area where Java stores objects and class instances. Unlike Stack Memory, data in Heap Memory remains accessible as long as there is a reference to it. Objects stored in Heap Memory are managed by Java’s Garbage Collector, which automatically removes unused objects to free up space.

Let's explore how heap memory works through an example.

class Person {
    String name;

    Person(String name) {
        this.name = name;
    }
}

public class HeapExample {
    public static void main(String[] args) {
        Person person1 = new Person("Alice"); // Stored in Heap
        System.out.println(person1.name);
    }
}

Here, the Person object is created in Heap Memory. Even though the reference person1 is in the Stack, the actual object exists in the Heap.

Key Differences Between Stack and Heap Memory

Stack Memory is fast, small, and automatically cleared when a method ends, while Heap Memory is larger, slower, and managed by the Garbage Collector. Stack stores primitive data types and method calls, whereas Heap stores objects and reference variables.

Conclusion

In this article, we explored Stack and Heap Memory in Java. The Stack stores method calls and local variables, clearing memory automatically when methods finish. The Heap stores objects and persists beyond method execution, managed by Java’s Garbage Collector.

Happy Coding!