Member-only story
Java StackOverflowError vs OutOfMemoryError with Examples
In this article, we’ll explore the differences between StackOverflowError and OutOfMemoryError, see code examples for both, and learn how to avoid them in real-world Java applications.
In Java, memory management plays a critical role in how your application performs and behaves. When the memory isn’t handled properly, the Java Virtual Machine (JVM) throws certain errors to alert developers that something has gone wrong. Two such common and confusing runtime errors are StackOverflowError
and OutOfMemoryError
.
Although both are Error types and are not meant to be caught under normal circumstances, they are quite different in cause, area of memory, and prevention strategies.
🔍 Quick Overview
Before we jump into the differences, let’s quickly define each.
🟡 What is StackOverflowError
?
A StackOverflowError
occurs when a thread’s call stack exceeds its limit — typically due to infinite or deep recursion.
Java uses stack memory to store method calls, local variables, and parameters. When the stack becomes full, the JVM throws this error.
🟢 What is OutOfMemoryError
?
An OutOfMemoryError
occurs when the heap memory is full and the JVM can no longer allocate space for new objects.
This usually happens when your application creates too many objects, holds onto objects unnecessarily, or there is a memory leak.
Quick Comparison Table
Example 1: StackOverflowError
The most common cause of StackOverflowError
is uncontrolled recursion — a method calling itself again and again with no stopping condition.
✅ Code Example:
public class StackOverflowDemo {
public static void recursiveMethod() {
recursiveMethod(); // infinite recursion
}
public static void main(String[] args) {
recursiveMethod();
}
}