Stackoverflow vs Outofmemory error


JVM divides its memory into two parts Heap memory and Stack : heap memory is used to store the instance objects whereas stack memory is used to store the calling hirarchy of the methods as well as the local variables of the method.
OutOfMemoryError is related to Heap. If you have large object which is refrenced and not eligible for garbage collection, and you are going to create new objects for which memory is not availbale , it will throw OutOfMemory error.
Solution : Always free your objects from reference so that objects will be eligible for GC.

StackOverflowError is related to stack. All your local variables and methods calls related data will be on stack. There is a single stack frame for every method call and all the data related to local variable and methods wiil be stored inside the stack frame. Stack frame is removed once execution is completed.
Solution: Avoid recursion for large iterations.