java.lang.StackOverflowError solution in java


In this Example we are getting the stack overflow error and understand how it will come.

Error Message :
Exception :
Exception in thread "main" java.lang.StackOverflowError
       at com.src.StackOverflowError.stackMethod(StackOverflowError.java:6)
       at com.src.StackOverflowError.stackMethod(StackOverflowError.java:6)


Error Description :

public class StackOverflowError {

       public static void stackMethod() {
              stackMethod();
       }
       public static void main(String[] args) {
              stackMethod();
       }

}
In the above program we are calling stackMethod() method inside the same method.
Means when we call the stackMethod() then it call again the same method (recursive)and it ll happen infinitely. And the error message will come still the stack size is full.


Solution:
We should go through the method and find where this repeat method calling , and need to fix accordingly.In the below Example we just limit to some number to avoid the Stackoverflow error.

package com.src;

public class StackOverflowError {
       static int num = 0;
       public static void stackMethod() {
              num++;
              if(num<3) {
              stackMethod();
              System.out.println("no stack overflow error");
              }
       }
       public static void main(String[] args) {
              stackMethod();
       }
}
Output:
no stack overflow error
no stack overflow error
no stack overflow error

Share this post :

Post a comment

Please share your valuable feedback and share this article in social media.

 
Support : Ranga Rajesh Kumar
Copyright © 2019. Error Solution - All Rights Reserved
Site Designed by Ranga Rajesh Kumar