It actually isn’t storing ‘past values’ at all. It stores the state of the program in the stack, with a frame for each method call containing data such as the current line the program is on. But there is only one value for the variable result
at any time, for the current method on top of the stack. That gets returned and used to compute result
in the frame that called this, and so on backwards, hence the bottom up behaviour you see.
One way to make this less confusing is to take recursion out of the picture temporarily. Suppose Java did not support recursion, and methods were only allowed to call other, different methods. If you wanted to still take a similar approach, one crude way would be to copy paste the factR
method into multiple distinct but similar methods, something like:
int fact1(int n){
int result;
if(n==1)return 1;
// Here's the difference: call the 'next' method
result=fact2(n-1)*n;
System.out.println("Recursion"+result);
return result;
}
Similarly define a fact2
which calls fact3
and so on, although eventually you have to stop defining new methods and just hope that the last one doesn’t get called. This would be a horrible program but it should be very obvious how it works as there’s nothing magical. With some thought you can realise that factR
is essentially doing the same thing. Then you can see that Java doesn’t ‘decide’ to multiply the values bottom up: the observed behaviour is the only logical possibility given your code.
solved In a recursive statment, how does java store the past values?