How to Solve StackOverflowError?

Fri, Nov 15, 2019

Read in 2 minutes

How to Solve java.lang.StackOverflowError?

In this article, you are going to see why the “StackOverflow” error occurs and how to fix. With this , you will explore the java stack and heap memory

Stack and Heap memory

When the java program starts it run, first the class will be loaded and it looks for the main method. If it founds the main method, then the main thread execution will get started.

stackOverflowDemo

If this program starts running, the class will be loaded and the main thread execution creates a memory frame in the stack.

So, the main method sits inside the stack and start executing. When it creates an object for the Test Class, the reference variable will be stored in the stack and its reference will be pointing the address in the heap.

Then The “recursion(5)” i.e recursion(n) method is called and that method call will go to the stack. Here , again the recursion method is called for n-1 parameter i.e recursion(4). Again recursion is called and it calls the recursion(3). Its going on like this for recursion(-1),recursion(-2) ..etc . Here the recursion(5) call is waiting for recursion(4) and recursion(4) is waiting for recursion(3) to complete and so on. So , the stack memory gets filled with this method calls and it overflows with the error message “Exception in thread “main” java.lang.StackOverflowError”.

How to fix this error :

public class Test {
    public static void main(String[] args) {
        Test t=new Test();
        t.recursion(5);
        }
   public void recursion(int n) {
          if(n>0)
           recursion(n-1);
            System.out.println(n);

                }
            }