×

Stack vs Heap in Java

In Java, whenever we declare an object or create a variable, whether it is an instance variable, local variable, or static variable, a certain memory is used to store the data. The amount of data or size is determined by the type of data type declared. In Java, there are two types of data, primitive and non-primitive.

Primitive data types:

TypeSize (in bits)
byte8
short16
int32
long64
float32
double64
char16
boolean1

Non-primitive data type:

  1. Class
  2. Object
  3. String
  4. Array
  5. Interface

There are significant distinctions between primitive and non-primitive data types, which are as follows.

  1. The primitive data types are initialized and declared while keeping the first letter in the small case. In contrast, the non-primitive datatypes are initialized and declared while keeping the first letter in a large case. Because non-primitive data types are treated as objects in Java. For example:
String st = "Sahil"; // non- primitive data type
int a = 100;        //primitive  data type 
  • Variables in primitive data types can only store one value at a time, whereas non-primitive data types allow us to store numerous values of the same or distinct types.
  • For primitive type variables, the stack retains all of the data, whereas, for reference types, the stack holds a pointer to the object on the heap.

Java's memory management plays an important role in its functionality. Java Virtual Machine properly uses both the memory to execute the program. And thus, to do so, the memory in Java is divided into the following types: stack memory and heap memory.

Stack Memory

Stack memory is also known as Java's temporary memory, storing variables and order of method execution. It uses a linear data structure. The stack implements the concept of LIFO order. To understand how the stack works, imagine a pile of books. The only way to take out a book lying in the middle of the pile of books is by taking out books above it one by one.

Similarly, stack stores data in a pile or a stack. To access the data at the bottom, you need to remove all the above data. It implements the following interfaces.

  • List
  • Iterable
  • Collection
  • Cloneable
  • RandomAccess
  • Serializable

It performs the following operations:

empty ()

This is a return type method; return true if the stack is empty.

peek ()

This is a return type function that returns the stack's top element. When the stack is empty, this function throws an EmptyStackException.

pop ()

This return type function returns the top element from the stack. This method invokes EmptyStackException when the stack is empty.

push ()

Adds a new element to the stack's top.

Heap Memory

It is used when we need is to store object classes and dynamically allocate memory. The memory is created when the Java Virtual Machine initiates its function, and the allocation of size may increase or decrease. Whenever a new object is created or declared, space is given to it in heap memory, while the reference variable of the same object is stored inside the Stack Memory. Unlike the stack, the heap memory does not store the data in any order, i.e., it does not store memory continuously. It has a feature called Garbage Collector. It deletes all the objects which are no longer being used. When the heap memory has no space to store a new object, it invokes Java.lang.OutOfMemoryError.

String arr = new String ();
arr = "Sahil Deshmukh";

The reference variable arr is stored in stack memory in the above code, and its value Sahil Deshmukh is stored in heap memory. The heap memory is further segregated into the following parts: -

  • Permanent generation
  • Code Cache
  • Young generation
  • Old generation
  • Survivor Space

Difference Between Stack and Heap

Stack MemoryHeap Memory
It acts as Random-access memory for Java and stores variables, methods, and reference variables.It stores objects.
It implements the LIFO order.It does not implement any order and dynamically allocates memory.
Users are not permitted to alter changes or manipulate the memory.Users are allowed to alter the memory.
It is comparatively faster in allocating memory.It is comparatively faster in allocating memory.
It is comparatively smaller in size.It is comparatively larger.
It continuously allocates memory.It randomly allocates memory.
It is thread-safe since each thread has its stack.Correct code synchronization is essential as it is not a thread-safe.
When the stack’s size reaches its limits, It throws Java.lang.StackOverFlowError. When the heap memory has no space to store a new object, it invokes Java.lang.OutOfMemoryError.
The stack memory exists only as long as the current method is active.Once the current application is closed, the heap space also gets closed.

Related Topics

Sort Dates in Java

The Collection class's sort() method, which is a component of the Comparator mechanism, arranges the data in decreasing order. The Comparator interface can be used to accomplish the goal while...

4 minutes read.

Java Integer signum() method

The signum() method of Java Integer class returns the signum function of the specified int value. Syntax public static int signum (int i)  Parameters The parameter ‘i’ represents the value whose signum is to...

1 minute read.

Check whether Java is installed or not

As we know that there are various operating systems, to check whether Java is installed or not in Windows and Mac we use the following ways.           Windows Operating System: There are several...

2 minutes read.

Java Networking

Networking Networking is a way of communicating the devices. It is made up of various technologies like computers, switches, routers that are interconnected and share data among themselves. The two common network protocols: 1. TCP/IP TCP stands for...

10 minutes read.

Misc Operators in Java

In this article, we are going to learn about the misc operators in Java. Misc operators are nothing but the miscellaneous operators. The java programming language supports some of the...

4 minutes read.

Static() Function in Java

The static keyword in Java is suitable for variables, constants, and functions. The static keyword is mainly used to control storage so that it may be appropriately used. We shall...

3 minutes read.

Read the XLSX file in Java

Excel files contain cells; reading an excel file in Java differs from reading a word file. JDK doesn't have a direct API that can read or write Word or Excel...

3 minutes read.

How to Call a Method in Java

In Java, a method is a collection of statements that perform a specific task or action.It can accept data with the help ofitsarguments. It  is also called a function. In order...

9 minutes read.

How to create a linked list in Java

Introduction: The linked listing is one type of linear statistics shaped like an array. Not like arrays, linked listing factors aren't stored in a contiguous place. The elements have linked...

3 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.

String to JSON in Java

Nowadays, receiving data in JSON String format rather than XML is quite frequent. Java does not transform JSON String to JSON Object when dealing with JSON String. However, using the...

3 minutes read.

Date time API in java

Introduction: In this text, we can talk approximately Data time API in java. The java.time, java.util, java.sql, and java.text packages contain classes that represent dates and times. The following classes are...

4 minutes read.

Short Circuit Logical Operators in Java

When there are two or more relational expressions in a decision-making statement, logical operators are utilized to combine them. The logical operators short circuit and not-short circuit fall into two...

5 minutes read.

Stone Game in Java

In this tutorial, we will learn to design a stone game in Java. First of all, we will understand what is this game all about. We will grasp it through...

9 minutes read.

AbstractSet Class in Java

The AbstractSet class is used for the implementation of the Abstract Collection class and interface. It is the part of Collection Frameworks. In the AbstractSet, the implementation is same as the...

3 minutes read.

How to take String Input in Java

There are various ways to take String input in Java. In this section, we are going to discuss how to take String input in Java. There are following ways to...

5 minutes read.

How to Convert String to Object in Java

How to Convert String to Object in Java The Object is the super class of all classes. So you can assign a string to Object directly. There are two methods to...

3 minutes read.

Difference Between replace() and replaceall() in Java

In this article, you will be acknowledged about the replace() and replaceall() methods in java. Also, most importantly you will be acknowledged the differences between them along with the example...

4 minutes read.

Morris Traversal for Inorder in Java

Through Morris’s traversal, a tree is traversed without the aid of recursion or stacks. Based on the threaded binary tree, the Morris traversal is used. We perform internal modification throughout...

4 minutes read.

How to run java program in ubuntu

To run the java programming in ubuntu, we need to follow several steps: Let's see the process. Step1: Install the Java compiler or JDK to the system. To run the java program, we...

3 minutes read.