java - Call Main Recursively -
public class demo { static int i=0; public static void main(string args[]) { system.out.println("hello"+(i++)); main(args); } } in program calling main instance variable.
it runs upto point after hello prints gives stackoverflow exception.
so put int find how many times gets printed.
i run program gives exception after i=4158.
but run several times gives exception @ different value of 4155,4124,4154 etc.
as know here stackoverflow generated because of bad or unconditional recursive call.
i tried figure out don't know what's happening.
i want know why after 4158 (or other values) ?
is dependent on system or dependent on program?
first, you're shadowing args variable. args defined in field isn't going regarded same args you're attempting recursively call in main.
second, recursion runs out, that's dependent on how memory have allocated application, , else in memory @ time. if gave 2gb (or more) of space work with, recursion still run out - @ higher value.
as for-instance, when run -xmx6g:
10791 10796 10789 the number different due else os running.
now, reason runs out: your calls placed on stack, not finite place in memory; can (and does) run out.
every time call function in java, goes onto stack.
first time through: > main(0) main() called, it's on bottom of stack.
if call main() again, call of gets placed on stack:
second time through: > main(1) > main(0) for simple applications, handful of calls (under 100) ever put onto call stack, , lifecycle short enough don't last on call stack long.
however, application different, since it's lacking known base case. use decide stop recursing.
take, example, famous factorial function, states:
{ 1 if n = 0 n! = < { n * (n-1)! if n > 0 we have our base case: if n = 0, don't continue recurse further. otherwise, keep on goin'.
here's looks in code:
public long factorial(int n) { return n == 0 ? 1l : n * factorial(n-1); } once i've reached base case, stop adding calls stack - begin resolving them.
here's sample of factorial(4) looks like:
> factorial(4) > factorial(3) > factorial(2) > factorial(1) > factorial(0) > 1 > 1 * 1 > 1 * 1 * 2 > 1 * 1 * 2 * 3 > 1 * 1 * 2 * 3 * 4 so, say: if you're going recursive function, make sure recursion can end. otherwise, you'll running issue time.
Comments
Post a Comment