StackOverflowError Vs OutOfMemoryError In Java

In this post, we will learn the difference between "StackOverflowError" and "OutOfMemoryError"
in Java. This is a frequently asked question in Java interviews for beginners. Let's dive into it.

Difference between "StackOverflowError" and "OutOfMemoryError" in Java

Feature StackOverflowError OutOfMemoryError
Cause Occurs when the call stack of a program exceeds its maximum allowed depth. Occurs when the Java Virtual Machine (JVM) is unable to allocate more memory for an operation.
Type of Error Is a runtime error. Is a runtime error.
Scenario Usually caused by excessive or infinite recursion in methods. Usually caused by allocating too many objects, or when objects are not being properly garbage collected.
Exception Class Extends the "Error" class. Extends the "Error" class.
Handling Generally not handled by the program as it indicates a severe error condition. Generally not handled by the program as it indicates a severe error condition.

Example

Let's create examples to demonstrate the difference between StackOverflowError and OutOfMemoryError in Java. 

StackOverflowError: 

StackOverflowError occurs when the stack size of a thread is exceeded. This typically happens when a method calls itself in a recursive manner indefinitely without a proper termination condition, leading to the stack memory being exhausted.
public class StackOverflowExample {
    public static void recursiveMethod() {
        recursiveMethod(); // Recursive call without a termination condition
    }

    public static void main(String[] args) {
        try {
            recursiveMethod();
        } catch (StackOverflowError e) {
            System.out.println("StackOverflowError occurred!");
        }
    }
}

Output:

StackOverflowError occurred!
In the example above, the recursiveMethod() is called recursively without any termination condition, causing the stack size to be exceeded, and resulting in a StackOverflowError.

OutOfMemoryError: 

OutOfMemoryError occurs when the Java Virtual Machine (JVM) cannot allocate enough memory to fulfill the memory requirements of an application. This can happen due to reasons like excessive object creation or large data structures that exceed the available heap memory.
import java.util.ArrayList;
import java.util.List;

public class OutOfMemoryExample {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        try {
            while (true) {
                list.add(1); // Continuously adding elements to the list
            }
        } catch (OutOfMemoryError e) {
            System.out.println("OutOfMemoryError occurred!");
        }
    }
}

Output:

OutOfMemoryError occurred!
In the example above, we create an ArrayList and continuously add elements to it inside a loop without any termination condition. Eventually, the heap memory is exhausted, leading to an OutOfMemoryError.

Note: Both StackOverflowError and OutOfMemoryError are runtime exceptions, and in real-world applications, they should be handled with proper exception handling mechanisms, or better yet, avoiding the situations that cause these errors.


Comments