- In the initial call to factorial,
n=5, and is pushed on the stack.
- Then the else is triggered so 4 is
passed to factorial, and is also
pushed onto the stack.
- Then the else is triggered so 3 is
passed to factorial, and is also
pushed onto the stack.
- Then the else is triggered so 2 is
passed to factorial, and is also
pushed onto the stack.
- Then the else is triggered so 1 is
passed to factorial, and is also
pushed onto the stack.
- Then the else is triggered so 0 is
passed to factorial, and is also
pushed onto the stack.
- The if gets triggered and 1 is
returned to the calling factorial.
- The if gets triggered and 2 * 1 is
returned to the calling factorial.
- The if gets triggered and 3 * 2 is
returned to the calling factorial.
- The if gets triggered and 4 * 3 is
returned to the calling factorial.
- The if gets triggered and 5 * 4 is
returned to the calling factorial.
The stack also gets cleaned up, however that gets too tedious to type. Essentially all values in a method call are pushed onto the stack, and popped off the stack on the methods return. This keeps them separated between recursive calls.