Search code examples
javascjp

why it throws StackOverflowError?


   public class ClassA {
        public void count(int i)
        {
            count(++i); //throws StackOverFlowError
        }
        public static void main(String[] args) {
            ClassA a = new ClassA();
            a.count(3);
        }
    }

when I debug the code I can see that its calling count method inside the count method, but after the pre-increment is done why it keeps incrementing i variable without exiting the method?


Solution

  • You don't have a termination condition for your recursion function, The count method is being called again and again and you will get stack overflow error.

    Check the below link for more info Stack overflow link