Side-by-side comparison of OutOfMemoryError and StackOverflowError — understand the differences, causes, and fixes.
OutOfMemoryErrorThe JVM has exhausted its available heap memory.
The application allocates more objects than the heap can hold. This can be caused by memory leaks, loading large datasets into memory, or insufficient heap size for the workload.
Increase heap size with -Xmx JVM flag. Profile the application for memory leaks using tools like VisualVM. Use streaming or pagination for large data sets. Close resources properly to allow garbage collection.
StackOverflowErrorThe call stack has exceeded its maximum size, usually due to deep or infinite recursion.
A method calls itself recursively without a proper base case, or mutual recursion between methods creates an infinite loop. Each method call consumes stack space until the limit is reached.
Add or fix the base case in recursive methods. Convert recursion to iteration. Increase the stack size with -Xss JVM flag. Check for accidental infinite recursion in constructors or toString methods.