Difference Between Stack and Heap Memory in Java



JVM has divided memory space between two parts: one is Stack and another one is Heap space. Stack space is mainly used for storing order of method execution and local variables.

Stacks always store blocks in LIFO order whereas heap memory uses dynamic allocation for allocating and deallocating memory blocks. 

Memory allocated to the heap lives until one of the following events occurs :

  • Program terminated 
  • Memory free 

What is a Heap memory?

Heap memory is allocated for storing objects, arrays, and JRE (Java Runtime Environment) classes. Memory may be allocated at random address and automatically free memory that is not in use.

Example

The following is an example of a heap in Java:

public class HeapExample {
    public static void main(String[] args) {
        int[] numbers = new int[3];  // Array object in heap
        numbers[0] = 5;
        numbers[1] = 10;
        numbers[2] = 15;

        for (int num : numbers) {
            System.out.println(num);
        }
    }
}

The output of the above Java program is:

5
10
15

What is a Stack memory?

Stack memory is used to store items that have a very short life, such as local variables and reference variables of objects. It follows the LIFO (Last-In First-Out) principle and is automatically managed during method calls and exits.

Example

The following is an example of stack in java:

public class StackExample {
    public static void main(String[] args) {
        int a = 10;   // stored in stack
        int b = 20;   // stored in stack
        int sum = add(a, b);  // method call adds a new frame on the stack
        System.out.println("Sum: " + sum);
    }

    public static int add(int x, int y) {
        int result = x + y;  // local variable in stack
        return result;
    }
}

The output of the above Java program is:

Sum: 30

Difference Between Stack and Heap Memory

Below are the differences between Stack and Heap Memory:

Sr. No. Key Stack Heap Memory
1
Basic
Stack memory is used to store items which have a very short life like local variables, a reference variable of objects 
Heap memory is allocated to store objects and JRE classes.
2
Ordering 
The stack is always reserved in a LIFO (last in first out) order
Heap memory is dynamic allocation there is no fixed pattern for allocating and deallocating blocks in memory 
3
Size
We can increase stack memory size by using JVM parameter -XSS
We can increase or decrease heap memory size by using JVM option -Xms and -Xmx
4
Visibility 
Variables are visible to only to owner thread 
It is visible to all threads 

Exception
JVM will throw java.lang.StackOverFlowError
JVM will throw java.lang.OutOfMemoryError
Updated on: 2025-04-15T19:12:52+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements