What is StackOverflowError, when it occurs with example?


When a program attempts to use more space than is available on the call stack the stack is said to overflow, typically resulting in a program crash. A call stack is a stack data structure that stores information about the active method of a program. A stack overflow occurs when an application recurses too deeply. One cause of StackOverflowError is a method calling itself without exit condition.

Example:

/**
 *
 * @author Navindra Jha
 */
public class Main {

    public static void main(String[] args) {

        new Friend().hello();
    }
}

class Friend {

    public String hello() {
        return "Room: " + this.hello();
    }
}

Output:

Exception in thread "main" java.lang.StackOverflowError

No comments:

Post a Comment