Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Stack Memory?
3.
Working of Stack Memory
4.
Example of Stack Memory
4.1.
Implementation
4.2.
Java
5.
Advantages of Stack Memory
6.
Disadvantages of Stack Memory
7.
What is Heap Memory?
8.
Working of Heap Memory
8.1.
New Generation or Young Generation
8.2.
Old Generation or Tenured Generation
8.3.
Permanent Generation
9.
Example of Heap Memory
9.1.
Implementation
9.2.
Java
10.
Advantages of Heap Memory
11.
Disadvantages of Heap Memory
12.
Difference Between Stack Memory And Heap Memory in Java
13.
Frequently Asked Questions
13.1.
What is the order memory allocation in heap memory?
13.2.
Is stack memory RAM or ROM?
13.3.
Why stack is faster than heap?
13.4.
What is the size of stack memory?
13.5.
Is stack memory LIFO or FIFO?
13.6.
What are the two types of heap?
14.
Conclusion
Last Updated: Mar 27, 2024
Easy

Stack Memory and Heap Memory in Java

Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Have you ever thought about how local variables and instance variables are stored in memory? Do you know the working of stack and heap memory? If not, then don’t worry. We will clear all your doubts.

stack and heap memory in java

In this article, we will discuss about Stack Memory and Heap Memory in Java and their working. We will also discuss the differences between them. Moving forward, let’s first understand about Java.

What is Stack Memory?

The memory space that stores local variables and object references is known as stack memory. The stack memory is created whenever a method is called. The memory allocation takes place in LIFO (Last In, First Out) order. Let’s suppose, with a method call, a thread is created. Then, the stack memory will be allocated to each thread at runtime. Moving forward, let’s understand the workings of stack memory in brief.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Working of Stack Memory

In a program, whenever a method is called during its execution, a memory block is created in the stack memory. Inside this memory block, all object references and local variables are stored. The method is executed, and after its execution is done, the created memory gets cleared from the stack memory automatically. The stack memory becomes again available for use. We can say that stack memory works in such a way that it stores(push) the data temporarily and pop them out after the execution is done. 

Example of Stack Memory

Let’s make a program to understand stack memory more clearly.

Implementation

  • Java

Java

class Solution {
   public static void main(String[] args) {
           int n = 10;
           n = ninja(n);
           System.out.println("n = "+n + " is returned and the memory block is cleared.");
   }
   public static int ninja(int n) {
       System.out.println("Inside ninja method.");
       return n;
   }
}

 

Output

Inside ninja method.
n = 10 is returned and the memory block is cleared.

 

Explanation

In the above code, we have made a method named ninja. We have declared a variable n inside the main function. A memory block is allocated for the main method, where the value will be stored. When the ninja method is called, a new block of memory will be allocated in the stack memory. When the execution of the ninja method is completed and the value is returned, then the memory block for the ninja method will be cleared. And now, the main method also completed its execution, so the memory block for the main method will also be cleared.

For better understanding, run this code on Online java compiler.

Advantages of Stack Memory

There are some advantages of using stack memory few of them are mentioned below:

  • It has fast access to the memory
     
  • Using stack memory, memory is automatically managed and cleaned up
     
  • There is no fragmentation in the stack memory

Disadvantages of Stack Memory

Along with some advantages, there are some disadvantages of using stack memory few of them are mentioned below:

  • It is of fixed size. Once the stack size is determined, it cannot be changed during runtime
     
  • It is of limited memory size. It is limited in size, which may cause a stack overflow error
     
  • It is not having any memory sharing

What is Heap Memory?

The memory space a computer program uses to store objects dynamically created during runtime is called heap memory. It is that space of the memory which is shared by all threads of an application and is typically managed by the operating system or runtime environment. The heap is dynamically allocated at runtime. It means that memory can be allocated and deallocated as needed, making it suitable for storing objects of unknown or variable size. The memory allocation takes place dynamically in random order. The size of the heap memory is large. It can be increased and decreased by the JVM options Xmx and Xms(where Xmx and Xms specify the maximum and minimum memory allocation pool for a JVM). Moving forward, let’s understand the working of heap memory in brief.

Working of Heap Memory

The heap memory is further divided into three parts. These parts are

  1. New Generation or Young Generation
     
  2. Old Generation or Tenured Generation
     
  3. Permanent Generation
     

Let’s understand each of them.

New Generation or Young Generation

Inside this memory space, the allocation of objects that are newly created takes place. There are three further parts of a new generation: 

  • Eden: This space is responsible for the allocation of newly created objects.
     
  • Survivor 1: The objects are moved to Survivor 1 after a minor garbage collection takes place. The minor garbage collection only takes place after Eden is full. 
     
  • Survivor 2: Similarly, the objects are moved here from Survivor 1 after the minor garbage collection.
     

Old Generation or Tenured Generation

Inside this memory space, the surviving objects from the new generation are stored. The major garbage collection is run in order to collect dead objects.

Permanent Generation

Inside this memory space, the metadata about the methods and classes are stored. The full garbage collection takes place, and this space is cleaned completely.

Example of Heap Memory

Let’s make a program to understand about heap memory more clearly.

Implementation

  • Java

Java

import java.util.ArrayList;
import java.util.List;

class Solution {
   public static void main(String[] args) {
           List<String> ninjaList = new ArrayList<>();

           ninjaList.add("Ninja 1");
           ninjaList.add("Ninja 2");
           ninjaList.add("Ninja 3");
           ninjaList.add("Ninja 4");
           ninjaList.add("Ninja 5");

           System.out.println(ninjaList);
   }
}

 

Output

[Ninja 1, Ninja 2, Ninja 3, Ninja 4, Ninja 5]

 

Explanation

In the above code, the array list of strings named ninjaList is stored in allocated memory in a heap. 

Advantages of Heap Memory

There are some advantages of using heap memory few of them are mentioned below:

  • Heap memory has dynamic memory allocation of memory
     
  • Using heap memory, memory can be allocated and deallocated whenever needed
     
  • It is not having any memory wastage

Disadvantages of Heap Memory

Along with some advantages, there are some disadvantages of using heap memory few of them are mentioned below:

  • It is slower than stack memory because of additional overhead in memory allocation and deallocation
     
  • Using heap memory, fragmentation can occur, leading to memory being spread across multiple non-contiguous blocks
     
  • It can have memory leaks if a program fails to deallocate the memory which is not needed

Difference Between Stack Memory And Heap Memory in Java

The differences between stack and heap memory in Java are as follows.

Parameter Stack Memory Heap Memory
Application The stack memory stores local and reference variables. The heap memory stores the created objects.
Memory Space This memory space is smaller in size. This memory space is larger in size.
Throws an error We may get a StackOverflowError error if there is no space left for any more method calls. We may get an OutOfMemoryError error if there is no space left for the allocation of objects.
Order  Memory allocation takes place in LIFO order. Memory allocation takes place in random order.
Efficiency The stack memory is fast. The heap memory is slower than stack memory.

Read more, Difference Between List and Set

Frequently Asked Questions

What is the order memory allocation in heap memory?

In heap memory, there is no order of memory allocation. It takes place dynamically in random order.

Is stack memory RAM or ROM?

Stack memory is typically implemented using RAM (Random Access Memory). RAM is a type of computer memory that allows data to be read from and written to quickly in random order. 

Why stack is faster than heap?

The stack is faster than the heap for memory allocation and deallocation, but the heap is still necessary for more complex data structures and larger amounts of memory that cannot fit on the stack.

What is the size of stack memory?

The size of stack memory is typically limited by the operating system and the hardware architecture of the computer. But the default main stack size is 8MB.

Is stack memory LIFO or FIFO?

Stack memory is managed using a Last-In-First-Out (LIFO) data structure. In other words, the most recently added item to the stack is the first one to be removed.

What are the two types of heap?

Two main types of heap are min heap and max heap. Min heap is where the value of each parent node is less than or equal to the value of its children. On the other hand, the max heap is where the value of each parent node is greater than or equal to the value of its children.

Conclusion

In this article, we have discussed about Stack Memory and Heap Memory in Java and their working. We have also discussed the differences between them. To learn more about Java programming language, you can check out our other articles:

We hope this article helped you in understanding about stack and heap memory in Java. You can read more such articles on our platform, Coding Ninjas Studio. You can also consider our Mern Stack Course to give your career an edge over others.

Happy Coding!

Previous article
Happy Number in Java
Next article
Java garbage collection: What is it and how does it work?
Live masterclass