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;
    }

}
  1. 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.

0
Subscribe to my newsletter

Read articles from Dulsara Abeybandara directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Dulsara Abeybandara
Dulsara Abeybandara

Tech Enthusiast | Aspiring Software Engineer | Recursion & Algorithms Explorer I'm a passionate programmer from Sri Lanka, currently diving deep into the world of algorithms, data structures, and software systems. I love breaking down complex concepts into simple, practical tutorials to help others learn and grow. My journey is all about building a solid foundation in programming and sharing my insights on recursion, coding challenges, and software engineering. Follow along as I document my experiences, from solving algorithmic problems to building real-world software solutions. Let's learn together!