Understanding Java Memory Allocation: Stack vs. Heap
Tags: java, stack, heap, datastructures
Published: 2021-10-05 03:28:12

**Java Stack**

A Java stack is a portion of your Computer's memory that stores temporary variables created by all functions you run. It's used to run a thread and can include both short-term values and references to other objects. It employs a **LIFO** (last in, first out) data structure.

When a method is called, a new block in the stack is created for that method. All local values and pointers to other objects utilized by the process will be stored in the new block. When the procedure is finished, the new block is erased and made available for the following method. The things you'll discover here are solely helpful for that function and won't last beyond it.

This makes keeping track of the stack a breeze, as the most recently reserved block is also the first to be freed. The variables created for the method are saved in memory and can be accessed quickly.

Because all variables created on the stack are wiped forever when a method ends, the memory size of a Java stack is typically significantly smaller than that of a Java heap area.

An example of how to make a stack object is as follows:

``` 
void somefunction( )
{
    /* create an object "m" of class Member
    this will be put on the stack since the
    "new" keyword is not used, and we are
    creating the object inside a function
    */

    Member m;

} //the object "m" is destroyed once the function ends
```


**Java Heap**

The heap is a location where Java objects are stored. It is formed when the program is executed, and its size may change as the program executes. It's easy for it to fill up, and when it does, garbage collection is started. Objects that are no longer in use are eliminated in order to make room for new ones.

Unlike a **Java stack**, where memory is allocated when the program is compiled, a **Heap allocates Memory** while the program is run. When opposed to the direct and fast access of a stack, accessing variables stored here is a little slower.

A global memory pool is analogous to a Heap. If you need the data or variables to live longer than the method or function in question, the heap will be used for Memory Allocation. All of the functionalities are accessible through the items found here.

In addition, there is no set order in which blocks in a heap should be reserved. You can allocate blocks at any time and then release them as needed. As you might expect, keeping track of the sections that are free and can be allocated is much more difficult, but it can be divided into two generations or sub-areas.

The young space (or nursery) and the old space are the two sub-areas. The memory allocation for new objects is usually done in the young space. Garbage collection occurs when the young space is filled. The youthful space is often used by short-term or transient things. When compared to a heap with no divisions, this aid speeds up garbage collection.

An example of how to make an item on the Heap is as follows:

```
void somefunction( )
{
    /* create an object "m" of class Member
      this will be put on the heap since the 
      "new" keyword is used, and we are 
      creating the object inside a function
    */
  
    Member* m = new Member( );
  
    /* the object "m" must be deleted
      otherwise a memory leak occurs
    */

    delete m; 
} 
```

**Stack and Heap's Similarities and Dissimilarities**

>Both of these methods are used by Java to allocate memory, and both are stored in RAM. To make things simpler, heap is utilized for dynamic memory allocation and stack is used for static memory allocation.

Where is it kept? Variables allocated on the stack can be accessed directly from memory, allowing them to run very quickly. Objects on the heap, on the other hand, take longer to access.

When will the allocation take place? When the application is compiled, memory is allocated on the stack. Meanwhile, when the program is started, it starts on the heap.

And, since this is the case, if you wish to use the stack, you'll need to know exactly how much data and memory you'll need before compiling. The stack also has the problem of not being able to manage large blocks of variables that require a lot of memory. You should use heap if you don't know how much data you'll need at runtime or if you require memory for a large amount of data.

**In a Nutshell…**

**Stack:**

As methods and functions add and destroy local variables as needed, the stack's size will change.
Without you having to control the memory allocation, memory is allocated and then freed.
The size of a stack is limited, and this varies depending on the operating system.
Variables stored on the stack remain valid for as long as the function that created them is active.

**Heap:**

Memory is not controlled automatically, and it is not handled as closely by the central processing unit as stack is. When these blocks are no longer required, you must clear the allotted RAM yourself.
Memory leaks are common in heaps, where memory is allocated to useless objects and not available to other processes.
The heap has no size restrictions.
Objects on the heap are much slower to access than those in the stack. It's also slower to write to the heap's memory.

Stack is more convenient and faster to use, but it has a number of drawbacks that you can overlook if you utilize heap.

>**When do you use "Stack"?**

Only local variables that take up a small amount of memory can be stored on the stack. The best part is that memory management and allocation will not be a problem for you, and access to these objects will be lightning quick. It suffers from size restrictions and the inability to resize variables on the stack.

>**When do you use "Heap"?**

If there are variables that need to be accessed worldwide rather than only by the procedures and functions that produced them, you use the heap to allocate memory. Because it has no memory size restriction, heap is also useful when you need a lot of memory. The variables in the heap can also be resized.


**Finally, I'd want to state that**

Java allocates memory in two ways: stack and heap. When you have variables that require global access, heap is the way to go, whereas stack is the way to go for local variables that just require a limited amount of memory. When it comes to writing better Java applications, knowing when and how to use a stack and a heap is crucial.

When dealing with memory leaks, it's also beneficial to understand how memory allocation works.