The code as stated gives the wrong answers; line 5 should read return 1;
, not return -1;
.
Java computes a call to the power
method by.. invoking it. This is no different here, it might just confuse you a bit because we're calling the power method from within the power method. Which in java is fine.
So, let's try power(3, 4)
as an example.
Java will first check if that 4 is below 0. It isn't, so skip that. Then if it is 0. It is not, so skip that. Then it'll return the result of the expression (filling in the variable values): return 3 * power(3, 4 - 1)
. To calculate that, power(3, 3)
must be evaluated first.
So java... does that. It remembers its half-way done work on power(3, 4)
(it does this 'on the stack') and now goes to calculate power(3, 3)
. The answer is to evaluate return 3 * power(3, 2)
. So, java remembers half of the work done for power(3, 3)
and goes to calculate that. The answer is the result of return 3 * power(3,1)
. You guessed it, remember our work and invoke power yet again: return 3 * power(3, 0)
but finally we're out: The method call power(3, 0)
is resolved by the second 'if', thus, return 1;
happens. power(3, 0)
successfully completed! Now power(3, 1)
can complete, then power(3, 2)
can complete, all the way up, and 81 is returned.