Prashnikaप्रश्निका
Code
About
‹ Back to the paper

Question 58

2 marks

Computer ScienceISC Computer Science - Competency Focused Practice Questions (CISCE, August 2024)Short answerRecursion

Answer the following question.

Following code gives a StackOverException. public class StackOverflow { public static void main() {…

Following code gives a StackOverException.
public class StackOverflow
{
    public static void main()
    {
        callMe();
    }
    public static void callMe()
    {
        callMe();
    }
}
Stack is a data structure whereas recursion is related to a method. Why does the above code give an exception with stack overflow?
Open in the Recursion visualiser

Answer

Answer

Each call to callMe() creates a new activation record (return address, parameters, local variables) that is pushed onto the call stack, and since callMe() calls itself with no base/terminating condition, calls keep being pushed and none are ever popped. The stack has a fixed maximum size, and once that limit is exceeded by the endless pushes, the JVM throws a StackOverflowError (reported as a stack overflow exception).