Differences between Stack and Heap Memory in Java

Stack is a type of temporary memory used by JVM ( Java Virtual Machine ) to store local method primitives variables, and method calls information.

Whereas in Heap is a type of memory used by JVM ( Java Virtual Machine ) to store references of objects (regardless where they are created) and String Pool.

Stack and Heap both are stored in the computer’s RAM (Random Access Memory).

 

Differences between Stack and Heap memory in Java

 Here are few differences between stack and heap memory in Java:

1) The main difference between heap and stack is that stack memory is used to store local variable and function call, while heap memory is used to store objects in Java. No matter, where object is created in code e.g. as member variable, local variable or class variable, they are always created inside heap space in Java.

2) If there is no memory left in stack for storing function call or local variable, JVM will throw java.lang.StackOverFlowError, while if there is no more heap space for creating object, JVM will throw java.lang.OutOfMemoryError .

3)  Each Thread in java has their own stack memory which can be specified using -Xss JVM parameter, similarly you can also specify heap size of Java program using JVM option -Xms and -Xmx where -Xms is starting size of heap and -Xmx is maximum size of java heap.

4)  The size of stack memory is very small as compared to that of heap memory in Java. The heap memory size is quite bigger than that of stack memory.

5)  The stack memory is kind of private memory of Java Threads, while heap memory is shared among all threads. In other words stack memory is not shared between multiple threads. Each thread will have its own stack memory while heap memory is shared between multiple threads, so each thread can get reference of any object.

6)   The garbage collection is not performed in case of stack as once a function call runs to completion; any data on the stack created specifically for that function call will automatically be deleted. In case of heap garbage collection is performed by the JVM (Java Virtual Machine) once all references for any object are null.