Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaStackOverflowError in Java with examples

StackOverflowError in Java with examples

StackOverflowError is an error which Java doesn’t allow to catch, for instance, stack running out of space, as it’s one of the most common runtime errors one can encounter.

The main cause of the StackOverflowError is that we haven’t provided the proper terminating condition to our recursive function or template, which means it will turn into an infinite loop.

When does StackOverflowError encountered?

When we invoke a method, a new stack frame is created on the call stack or on the thread stack size. This stack frame holds parameters of the invoked method, mostly the local variables and the return address of the method. The creation of these stack frames will be iterative and will be stopped only when the end of the method invokes is found in the nested methods. In amidst of this process, if JVM runs out of space for the new stack frames which are required to be created, it will throw a StackOverflowError.

For example: Lack of proper or no termination condition. This is mostly the cause of this situation termed as unterminated or infinite recursion.

Given below is the implementation of infinite recursion:




// Java program to demonstrate
// infinite recursion error
  
public class StackOverflowErrorClass {
    static int i = 0;
  
    // Method to print numbers
    public static int printNumber(int x)
    {
  
        i = i + 2;
        System.out.println(i);
        return i + printNumber(i + 2);
    }
  
    public static void main(String[] args)
    {
        // Recursive call without any
        // terminating condition
        StackOverflowErrorClass.printNumber(i);
    }
}


Runtime Error:

RunTime Error in java code :- Exception in thread “main” java.lang.StackOverflowError
at java.io.PrintStream.write(PrintStream.java:526)
at java.io.PrintStream.print(PrintStream.java:597)
at java.io.PrintStream.println(PrintStream.java:736)
at StackOverflowErrorClass.printNumber(StackOverflowErrorClass.java:13)
at StackOverflowErrorClass.printNumber(StackOverflowErrorClass.java:14)
at StackOverflowErrorClass.printNumber(StackOverflowErrorClass.java:14)
.
.
.

Note: Please run this on your system to see an error thrown, due to the stack size, this may not show error on online IDE.

How to fix StackOverflowError?

  1. Avoiding repetitive calls: Try to introduce a proper terminating condition or some condition for the recursive calls to ensure that it terminates.

    Given below is the implementation with proper terminating condition:




    // Java Program to demonstrate proper
    // use of terminating condition
      
    // Printing natural numbers
    public class stackOverflow {
        static int i = 0;
        public static int printNumber(int x)
        {
      
            i = i + 2;
            System.out.println(i);
      
            // Terminating condition
            if (i == 10)
                return i;
      
            return i + printNumber(i + 2);
        }
      
        public static void main(String[] args)
        {
            stackOverflow.printNumber(i);
        }
    }

    
    
    Output:

    2
    4
    6
    8
    10
    
  2. Increasing the Stack Size: The second method could be, if you notice that it’s implemented correctly still we see an error, then we can avoid that only by increasing the Stack Size in order to store the required number of recursive calls. This is achieved by changing the settings of the compiler.

    Cyclic Relationships between classes is the relationship caused when two different classes instantiate each other inside their constructors.

    StackOverflowError is encountered because the constructor of Class A1 is instantiating Class A2, and the constructor of Class A2 is again instantiating Class A1, and it occurs repeatedly until we see StackOverflow. This error is mainly due to the bad calling of constructors, that is, calling each other, which is not even required, and also it doesn’t hold any significance, so we can just avoid introducing them in the codes.

    Given below is the implementation of Cyclic Relationships Between Classes:




    // Java Program to demonstrate
    // cyclic relationship between class
      
    public class A1 {
        public A2 type2;
        public A1()
        {
      
            // Constructor of A2 is called
            // hence object of A2 is created
            type2 = new A2();
        }
      
        public static void main(String[] args)
        {
      
            // Cycle is started by
            // invoking constructor of class A1
            A1 type1 = new A1();
        }
    }
      
    class A2 {
        public A1 type1;
        public A2()
        {
      
            // Constructor of A1 is called
            // hence object of A1 is created
            type1 = new A1();
        }
    }

    
    

    Runtime Error:

    RunTime Error in java code :- Exception in thread “main” java.lang.StackOverflowError
    at A2.(A1.java:32)
    at A1.(A1.java:13)
    at A2.(A1.java:32)
    .
    .
    .

    Note: This will keep repeating, Infinite Recursion is seen by these infinite cyclic calls.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments