Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is a StackOverflowError vs an OutOfMemoryError in Java? Java में StackOverflowError और OutOfMemoryError में क्या अंतर है?

Answer
ErrorCauseCommon trigger
StackOverflowErrorCall stack exceeds its maximum sizeInfinite or excessively deep recursion
OutOfMemoryErrorHeap (or other memory area) exhaustedMemory leaks, loading huge datasets, too many objects retained
// StackOverflowError example
public void recurse() {
    recurse();  // no base case - each call adds a new stack frame
}
// recurse();  // java.lang.StackOverflowError

// Fixed with a proper base case
public int factorial(int n) {
    if (n <= 1) return 1;  // base case stops the recursion
    return n * factorial(n - 1);
}

// OutOfMemoryError example - heap space exhausted
import java.util.*;
public void memoryLeak() {
    List<int[]> list = new ArrayList<>();
    while (true) {
        list.add(new int[1000000]);  // keeps allocating, never released
    }
}
// java.lang.OutOfMemoryError: Java heap space

// Both extend Error (not Exception) since they represent serious,
// often unrecoverable JVM-level problems that applications generally
// should NOT try to catch and continue from

// Both ARE technically catchable, but doing so is usually a bad idea:
try {
    recurse();
} catch (StackOverflowError e) {
    System.out.println('Caught, but the program state may be unstable now');
}

// Increasing JVM memory limits (doesn't fix underlying leaks, just delays them)
// java -Xmx512m -Xss1m MyApp   (-Xmx: heap size, -Xss: thread stack size)
ErrorकारणCommon trigger
StackOverflowErrorCall stack अपनी max size से बड़ा हो जाएInfinite या बहुत गहरी recursion
OutOfMemoryErrorHeap memory खत्म हो जाएMemory leaks, बहुत बड़ा data
public void recurse() {
    recurse();  // कोई base case नहीं
}
// java.lang.StackOverflowError

public int factorial(int n) {
    if (n <= 1) return 1;  // base case recursion रोकता है
    return n * factorial(n - 1);
}

import java.util.*;
public void memoryLeak() {
    List<int[]> list = new ArrayList<>();
    while (true) {
        list.add(new int[1000000]);  // कभी release नहीं होता
    }
}
// java.lang.OutOfMemoryError: Java heap space

// दोनों Error extend करते हैं (Exception नहीं), serious JVM problems हैं

try {
    recurse();
} catch (StackOverflowError e) {
    System.out.println('Caught, पर program state अस्थिर हो सकता है');
}

// JVM memory limits बढ़ाना
// java -Xmx512m -Xss1m MyApp

Was this answer clear?