Road to Recursion
What is the Stack?
The stack is a special area in a computer's primary memory (RAM) that manages method calls and local variables.
What is a Stack Frame?
A stack frame is a block of memory allocated on the stack when a method is called.
Each stack frame contains:
- Local variables
- Method parameters
- Return address (stores where execution should continue after the method completes)
- Return value (only for non-void methods)
What happens when a method is called?
ex:
#include <iostream>
int addition(int x, int y) {
return x + y;
}
int main() {
int a = 10;
addition(5, 3);
return 0;
}
public class Test {
public static void main(String[] args) {
int a = 10;
addition(5, 3);
}
public static int addition(int x, int y) {
return x + y;
}
}
- When main() starts, a stack frame for main() is created.
2. When addition(5, 3) is called, a new stack frame for addition() is pushed onto the stack.
3. After addition() finishes, its stack frame is popped, and execution resumes in main().
4. When main() finishes, the stack is emptied.