# Whenever we run a java program, the operating system will allocate some memory to the JVM. The JVM divides this memory into two parts. One is stack memory and the other is heap memory. The stack is used to execute methods, and the heap is used to store objects. When the stack is full, the JVM throws java.lang.StackOverflowError; when the heap is full, the JVM throws java.lang.OutOfMemoryError.
StackOverflowError
- The stack is used for method execution. For each method call, a block is created in the stack memory. Data related to the method (such as parameters, local variables, or object references) is stored in the block.
- When the method completes execution, the block is removed from the stack along with the data stored in it.
- Whenever we call a method, it must complete execution and leave the stack memory.
- If the method stays on the stack, then the stack will be full and the JVM will throw java.lang.StackOverflowError.
- OutOfMemoryError
The objects we create in Java are stored in heap memory. When these objects are no longer needed, they must be deleted from memory.
- The garbage collector will delete unnecessary objects from the heap memory.
- If our objects have live references, the garbage collector will not delete them. It only deletes those objects that have no live references.
- Whenever we call a method, it must complete execution and leave the stack memory.
- If there is no space left for the new object in heap memory, the JVM will throw java.lang.OutOfMemoryError.
-
The above is the detailed content of What is the difference between StackOverflowError and OutOfMemoryError in Java?. For more information, please follow other related articles on the PHP Chinese website!