LoLisSuck LoLisSuck - 2 years ago 55
Java Question

Using recursion but encounter "Source not found" and Stackoverflow

I wrote a function to recursively add and print 0~n.

i thought BigInteger can store and manipulate large number.

But I encountered some bug.
I tried to use sysout and set upBoundStr to 10000.

The bug is still there.
Could someone tell me what happened?

My code

package playground;

import java.math.BigInteger;

public class play1
String initStr = "0";
String dStr = "1";
String upBoundStr = "1000000";
private BigInteger i = new BigInteger(initStr);
private BigInteger diff = new BigInteger(dStr);
private BigInteger upBound = new BigInteger(upBoundStr);

public void countBigInteger()
i = i.add(diff);

public static void main(String args[])
play1 p1 = new play1();


enter image description here

enter image description here

Answer Source

The call stack has a limited size. I tried your code and got StackOverflowError after printing 6600 numbers. This means that the call stack had enough space for 6600 method calls before it ran out of space. That's the risk of running such a deep recursion.

This has nothing to do with BigInteger, since this code fails before you even get near the max value of int (or even short).

If the goal of this code is to test recursion, you found out that deep recursion has limits. If that code serves some other purpose, you can easily re-write it without using any recursion at all.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download