Tuesday, 26 March 2019

Stack Memory vs Heap Memory


Stack Memory –
Stack memory can be considered as local/private memory, all the local variables and functions are defined in stack memory.
When stack memory is full, Java runtime throws java.lang.StackOverFlowErrorwhereas

Heap Memory –
Heap memory is used to store Objects and JRE classes. This is publically available for all running the threads means heap memory is globally accessible in the application.
When heap memory is full, it throws java.lang.OutOfMemoryError: Java Heap Space error


Heap and Stack Memory in Java Program
public class MainTest {

private int classLvlVar = 0; // class level variable heap memory
      
       public static void main(String[] args) { // stack memory
              int localVar = 1; //stack memory
              // instance is created in heap memory while reference variable maintest will be in stack memory
              // which will refer to heap instance.
              MainTest mainTest =  new MainTest();
             
              System.out.println(localVar); // stack memory
              mainTest.getVar(); //stack memeory
             
       }
      
       private int getVar() {
              return classLvlVar//stack memory
       }
}


If there is no memory left in the stack for storing function call or local variable, JVM will throw java.lang.StackOverFlowError, while if there is no more heap space for creating an object, JVM will throw java.lang.OutOfMemoryError: Java Heap Space.


1 comment: