StackOverflowError occurs when stack memory is exhausted due to
excessive method calls, typically caused by infinite or very deep
recursion. OutOfMemoryError occurs when the JVM cannot allocate
more memory, usually because heap memory is exhausted by excessive
object creation or memory leaks
Java memory mainly has:
1. Stack Memory
2. Heap Memory
JVM Memory
│
├── Stack Memory
│ ├── Method calls
│ ├── Local variables
│ └── Function frames
│
└── Heap Memory
├── Objects
├── Arrays
└── Instance data
1. StackOverflowError
What Is It?
stack memory becomes full
Most Common Cause?
Infinite recursion
public class Main {
static void test() {
test();
}
public static void main(String[] args) {
test();
}
}
Final Error
Exception in thread "main"
java.lang.StackOverflowError
Stack Frames Growing and eventually stack full.
TOP
│
├── test()
├── test()
├── test()
├── test()
├── test()
│
BOTTOM
Every method call creates:
- stack frame
- local variables
- return address
Too many frames → overflow.
Common Causes of StackOverflowError
2. OutOfMemoryError
What Is It? Occurs when?
JVM cannot allocate more memory
usually in: heap memory
Most Common Cause : Too many objects
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<int[]> list = new ArrayList<>();
while(true) {
list.add(new int[1000000]);
}
}
}
What Happens Internally?
Each loop:
- creates huge array
- stores in heap
- references retained in list
Garbage collector cannot free memory.
Eventually: heap full
Final Error
java.lang.OutOfMemoryError:
Java heap space
Heap Growing and no space left.
Heap
│
├── Object
├── Object
├── Object
├── Object
├── Object
├── Object
│
FULL
Common Causes of OutOfMemoryError
StackOverflowError
- Usually easier to debug.
- Stack trace clearly shows recursion.
OutOfMemoryError
Can be very difficult:
- memory leaks
- object retention
- cache problems
- GC tuning
often require:
- heap dumps
- profilers
- memory analyzers
Important JVM Parameters
Stack Size -Xss
Example: java -Xss2m Main
Increase stack size.
Heap Size -Xmx
Example: java -Xmx2g Main
Increase heap size.
Can StackOverflowError Cause OutOfMemoryError?
Indirectly yes sometimes.
Huge recursion may:
create many objects
trigger memory exhaustion
But normally they are distinct problems.
Why Are These Errors and Not Exceptions?
Because:
- serious JVM resource exhaustion
- application usually cannot safely recover
Both extend:
java.lang.Error
not: Exception
Can We Catch Them?
Technically yes:
catch(StackOverflowError e)
or
catch(OutOfMemoryError e)
BUT usually: bad practice
Application state may already be unstable.



Top comments (0)