What I don't understand here is where the second value of i which is 1 come from.
Regardless of whether or not the method recurses, it always returns i
. So a call of foo(2)
will always return 2, even though it recurses while printing.
The output message here is confusing because it's not printing i
. It may help you to understand if you change it to:
public int foo(int i) {
if (i > 0) {
int recurse = foo(i - 1);
System.out.println("i: " + i + "; foo(i - 1): " + recurse);
}
return i;
}
Note that you'll get the result in "reverse" order because it'll print the result of calling foo(1)
while still within foo(2)
.