Difference between Stack and Heap memory in Java


JVM has divided memory space between two parts one is Stack and another one is Heap space. Stack space is mainly used for storing order of method execution and local variables.

Stack always stored blocks in LIFO order whereas heap memory used dynamic allocation for allocating and deallocating memory blocks. 

Memory allocated to the heap lives until one of the following events occurs :

  • Program terminated 
  • Memory free 

In contrast, the memory allocated to stack lives until the function returns. Below are the differences.

Sr. No.KeyStackHeap Memory
1
Basic
Stack memory is used to store items which have a very short life like local variables, a reference variable of objects 
Heap memory is allocated to store objects and JRE classes.
2
Ordering 
The stack is always reserved in a LIFO (last in first out) order
Heap memory is dynamic allocation there is no fixed pattern for allocating and deallocating blocks in memory 
3
Size
We can increase stack memory size by using JVM parameter -XSS
We can increase or decrease heap memory size by using JVM option -Xms and -Xmx
4
Visibility 
Variables are visible to only to owner thread 
It is visible to all threads 
  5 
Exception
JVM will throw java.lang.StackOverFlowError
JVM will throw java.lang.OutOfMemoryError

Updated on: 18-Nov-2019

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements