Java / JDK, JRE, JVM, JIT
Difference between Stack and Heap memory in Java.
The main difference between heap and stack is that stack memory is used to store local variables and function call while heap memory stores objects in Java.
Each Thread in Java has its own stack whose size 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 the starting size of the heap and -Xmx is the maximum size of java heap.
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.
Size of stack memory is a lot lesser than the size of heap memory in Java.
Variables stored in stack is only visible to the owner thread while objects created in the heap are visible to all threads. Stack memory is a private memory of a Java Thread while heap memory is shared among all threads.
More Related questions...