I try very simple test:
public static void main(String[] args) {
test(2);
}
public static void test(int i) {
i--;
System.out.println("i="+i);
if (i < 0)
return;
System.out.println("test1");
test(i);
System.out.println("test2");
test(i);
}
Output:
i=1
test1
i=0
test1
i=-1
test2
i=-1
test2
i=0
test1
i=-1
test2
i=-1
I cannot understand why variable i in second call (test2) has value 0 after that already has 0 ?
Thanks.
I find indenting the output will help explain these things, each level here corresponds to the depth of the call stack (how many recursions deep you are), and the sequence corresponds to when these things are executed:
Notice that under each indentation level there are are invocations under the headings “test1” and “test2”, this is because you recursively call
testunder each of these headings, and so at each execution oftestyou recurse twice.Let’s backup a bit and take a simpler case, if you were to execute
test(1), you would expect to see:Because you call
testunder the headings “test1” and “test2” you’re causing two paths to be navigated, one path under the “test1” heading, and a second under the “test2” heading.When you call
test(2), your code roughly does this: (recursions omitted)…and remember, each time you call
test(1), your code roughly does this: (recursions omitted)If you replace each call in the first block with the output of the
test(1)block you’ll see it exactly generates your output.Basically, you get two
i=0prints because you recurse twice in each function call.