‹ Back to the paper
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?Answer
Answer
AIEach 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).
From ISC Computer Science - Competency Focused Practice Questions (CISCE, August 2024), question 58.