-5
   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?

kittu
  • 6,662
  • 21
  • 91
  • 185

5 Answers5

2

Its a recursive call (calling the same method itself). Basically recursive calls must have some exit criteria which is missing here.

As there is no exit criteria, the method is being called again and again and on each call it inserts a frame into the stack memory. Ultimately stack memory is getting overflown and hence the error

HJK
  • 1,382
  • 2
  • 9
  • 19
1

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

Community
  • 1
  • 1
Sunil Rajashekar
  • 350
  • 2
  • 18
1

Every method call has its own stack frames which keeps register contents and the object parameter passed to the method. All these hold memory space. When a call made recursive without any exit condition. For each and every call stack frames,register contents are generated and started consuming memory which leads to StackOverflow exception.

Mohan Raj
  • 1,104
  • 9
  • 17
0

As you said in your problem description, you are calling count(int) method recursively. It makes no difference if you pre-increment or post increment i. You need to write some exit condition to get out of this recursive call.

Ashishkumar Singh
  • 3,580
  • 1
  • 23
  • 41
0

The recursive call to count(++i) leaves behind a call stack frame that isn't reclaimed. In other languages with proper tail calls the stack frame would be reused when making the recursive call. Note that the call wouldn't terminate in that case.

ReyCharles
  • 1,772
  • 10
  • 30