Understanding Stack Memory and Heap Space in Java.
Tags: java, stack, heap
Published: 2024-03-11 09:59:58

In the Java ecosystem, The JVM which stands for Java Virtual Machine is what enables java codes machine readable for interpretation. Now when it comes to the memory management, the JVM has two main memory storage, which are the stack and heap.
The stack and heap are use extensively in data structures and algorithms for managing memory allocation.
In this tutorial guide, we'll explain what the stack and heap is all about, differences and code examples to illustrate them.

What is Java Stack Memory?
Generally, stack represents LIFO(Last In First Out) order which means the last  item inserted or added is the first item to be removed when accessing the stack. whenever a method is invoked, it is directly pushed into the stack and a new block of memory is allocated to the stack memory. This new block will store values of the variables used in the method. In Java, stacks memory are used for static memory allocation. Java stack stores method calls and local variables in the memory. Stack memory size is very small compared to the Heap memory.

**What is Java Heap Space?**
Java Heap space are large, open space memory used in java runtime. whenever we create or reference an object, it is usually created in the heap. it memory stores instance variables, objects and JRE classes.

**Differences Between Stack Memory and Heap Space in Java**
The Stack and Heap has different similarities both in size and efficiency. In this article we'll outline the core differences between the stack and Heap space in java.

1. In the memory management, Stack follows the LIFO order while the Heap does not follows any order, as it is a dynamic data structure and it's space complexity tends to be dynamic, allowing for flexible allocation and deallocation of memory.

2. The Stack is used for a single thread of execution while Heap is dynamic and robust is used by the entire application.

3. Whenever an object is invoked or created, it's stored automatically into the Heap memory, while the stack memory contains the local variables and reference to the new object created.

**How do Stack and Heap Works?**
Here, we use a code snippet to explain how the stack and heap works.

```
class Calculator {
    int num;
    public int add(int n1, int n2) {
        int r = n1 + n2;
        return r;
        // System.out.println("in add");
    }
}

public class Stack {
    public static void main(String[] args) {
        int data = 10;

        
        int n1 = 4;
        int n2 = 3;

        Calculator obj = new Calculator();
        Calculator obj1 = new Calculator();
        int result = obj.add(n1, n2);

        System.out.println(result);
        System.out.println(obj.num);
        System.out.println(obj1.num);
    }
}
```
 

The diagram below explains how the stack and heap memory are related with the above program


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aaqcqhjmnnmys0ydwkx1.png)
Now let's briefly explain each process in the diagram:

- In the stack memory we have the main and the add method. which the main contains variables with their keys and values:  data which contains the unused variable declared, obj and obj1 which are two instances of the Calculator class created in the stack and the result is represent the output of the given program. while the add method contains the n1, n2 respectively.

- Now the obj, obj1 are referencing to the object in the heap. where the exact memory for the Calculator objects is allocated in the heap space. All these referencing(IDs or addresses) employs or allows a way to access these objects properties and method in a more accessible way.

- In the heap memory side, it contains a `num = 10`, if you look at that num = 10 in our code that has int num;, the `int num`; is an instance variable. Here heap stores the instance variable in the heap memory. 

- In the heap memory, It also has an add() method which will store the executable code for add() function. When `obj.add(n1, n2)` is called in the main method, it accesses this `add()` method in the heap memory

**Conclusion**
Stack and Heap memory are great memory allocation when dealing with algorithm problem, understanding how they work interchangeably will help foster the usage between them. What else do you know about stack and Heap let's us know in the comment section.