To run a Java program, memory is required. This memory is allocated from the Operating System to JVM (Java Virtual Machine)and is divided into two parts, namely:
Stack memory is used when we call a method or run some thread. As we keep on calling methods, Present state of program and local variables are pushed to the stack memory. Once method is finished, its local variables are popped from the stack memory.
Here's the corresponding call stack. SP denotes the Stack Pointer.
Heap memory is used when we declare and initialize an object. This object can be an array, variable, constant, etc.
The memory provided by the operating system to run the Java program is limited, and so are Stack and Heap memory.
java.lang.stackOverflowError is raised when we run out of Stack memory. This can arise when we call a recursive method without proper terminating condition. If we keep on calling methods, state information keeps adding to the call stack, the Stack memory runs out of space. Here's an example of code which will throw this error.
To remove this error, proper terminating condition can be written. Lets add a terminating condition to the previous code snippet:
java.lang.outOfMemoryError is raised when we run out of Heap memory and memory isn't available for new Objects. This arises when we have live references to our object or we try to create a very large object. If an object has live reference, Garbage Collector doesn't remove it. Here's an example of outOfMemoryError.
To remove this error, make sure that you don't allocate large space to objects like in the above example and there are no live references to the objects.