group-icon
Java Developers
Group for Java developers and programmers. Ask questions and get answers related to Java programming
255 Members
Join this group to post and comment.
DHIRAJ LOTLIKAR
DHIRAJ LOTLIKAR
Information Technology
05 Feb 2019

StackOverflow error vs OutOfMemory error in java?

Whenever you run a java program or java application, operating system allocates some memory to JVM. JVM divides this memory into two parts. One is Stack and another one is Heap. Stack is used for execution of methods and heap is used to store the objects. When the Stack becomes full, JVM throws java.lang.StackOverflowError and when the heap becomes full, JVM throws java.lang.OutOfMemoryError

StackOverflowError In Java :

Stack is used for execution of methods. For every method call, one frame or block is created in the stack memory. The data related to method like parameters, local variables or references to objects are stored in this block. When the method finishes its execution, this block is removed from the stack along with data stored in it.

Whenever you call a method, it must finish its execution and leave the stack memory. If your methods are staying in the stack then stack will be full and JVM will throw java.lang.StackOverflowError.

In most of time, StackOverflowError occurs when your program is calling a method recursively without proper terminating conditions.

OutOfMemoryError In Java :

java.lang.OutOfMemoryError is thrown when the heap is full and JVM is unable to allocate the memory to new objects.

The objects you create in java are stored in the heap memory. When the objects are no more required, they must be removed from the memory. Garbage collector removes the unwanted objects from the heap memory. If your objects have live references, garbage collector doesn’t remove them. It removes only those objects which don’t have live references.

If there is no space left for new objects in the heap memory then JVM will throw java.lang.OutOfMemoryError.