How to resolve the "java.lang.stackoverflowerror" in Java

svg viewer

The java.lang.stackoverflowerror is indicative of serious problems that an application cannot catch (e.g., stack running out of space). It is usually caused by a no terminating ​condition of the recursive call.

Code

The following code prints the numbers and has no terminating condition. The java.lang.stackoverflowerror error occurs because the stack’s size has been completely occupied and can no longer be used.

class StackOverFlowExample {
public static void recursivelyPrint(int num) {
System.out.println("Number is: " + num);
if(num == 0)
return;
else
{
num +=1;
recursivelyPrint(num);
}
}
public static void main(String[] args) {
StackOverFlowExample.recursivelyPrint(1);
}
}

Solution

  • The simplest solution is to carefully inspect the stack trace and detect the repeating pattern of line numbers. These line numbers indicate the code that is being recursively called. Once you detect these lines, look for the terminating condition (base condition) for the recursive calls.

  • Once you have verified that the recursion is implemented correctly, you can increase the stack’s size in order to allow a larger number of invocations. The stack size can be increased by changing the settings of your compiler.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved