×

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

Application of Array in Java

In this article we are going to acknowledge about what the array is, types of arrays and their applications. What is an array? An array is often a set of interrelated elements...

4 minutes read.

Java Queue

The Java.util package has the interface Queue, which does extend the Collection interface. It is used to protect the parts that are managed using the FIFO approach. Being an interface, the...

5 minutes read.

Java vs Go

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

Java Math negateExact() Method

The negateExact() method of Math class returns the negation for the specified argument, throwing an exception if the result overflows an int or a long. Syntax: public static int negateExact (int a)public...

1 minute read.

How to Round Double Float up to Two Decimal Places in Java

It indicates 15 digits just after the decimal place in Java whenever a double data type is used in front of a variable. For example, when representing rupees and other...

4 minutes read.

Java Math.multiplyExact() method in Java

Java has an inbuilt math function called Math.multiplyExact() that returns the sum of the parameters. If the result exceeds an integer, an exception is thrown. There is no need to...

2 minutes read.

Java 8 filters list

A stream with the components of this stream that match the given predicate is provided by the streaming filter (Predicate predicate). This process is step-by-step. Because these operations are always...

4 minutes read.

Powerful Number in Java

We will define a powerful number in this article and write Java programs to determine whether a given number is a powerful number or not. Java coding interviews and academic...

6 minutes read.

this keyword in Java

The 'this' keyword is an essential notion in Java. We'll go through the 'this' keyword in depth and provide some examples of how it's used in Java. In Java, the term...

5 minutes read.

Java Enum vs Class

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four integrators named Club, Diamond,...

7 minutes read.

How to Create an Object in Java

How to Create an Object in Java An object can be defined as a run time entity that contains the blue printof the class. It means that all the member functions...

5 minutes read.

Java Strings

String class is the most used class in Java programming language. The string is the sequence of characters, which is treated as objects in Java. Creating String objects We create String objects...

5 minutes read.

Heap Sort in Java

Heap Sort in JavaHeap sort in Java uses the data structure binary heap, min-heap, or max heap to do the sorting of elements. Since min-heap always gives the minimum element first,...

8 minutes read.

Pernicious Number in Java

If the number of 1s in a number appearing in the binary representation is the prime number, such a number is known as a pernicious number. A pernicious number always corresponds to...

4 minutes read.

Java Linters

When it comes to programming, everyone makes mistakes. Errors are bad for developers since they are difficult to handle. But handling as many as possible errors will bring out the...

6 minutes read.

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

Java Math.multiplyExact() method

In java, we are provided with multiplyExact method in the Math module. This Math module belongs to the java.lang package. In general, this method returns the product of the provided...

2 minutes read.

Java Math signum() Method

The signum() method of Java Math class returns the signum function of the value. Syntax: public static double signum(double d)public static float signum (float d) Parameters: The parameter ‘d’ represents the floating-point value whose...

2 minutes read.

Differences between Set and List in Java

Set in Java: The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates...

6 minutes read.

Java Boolean toString() Method

The toString() method of Java Boolean class returns a String corresponding to this Boolean object. It returns a string value “true”, if the defined object is true else it returns...

2 minutes read.