Trusted answers to developer questions

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

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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.

RELATED TAGS

how
resolve
java.lang.stackoverflow
error
java
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?