Java Learner logo

Module 4: Methods and Code Reusability

Lesson focus

The Call Stack Explained

Visualize how Java keeps track of method calls using the call stack, and understand how stack overflow errors occur.

What is the Call Stack? The call stack is a data structure that the JVM uses to manage method invocations. It works on a Last-In, First-Out (LIFO) principle.

How it Works:

  • When your program starts, the main method is placed on the bottom of the stack.
  • Every time a new method is called, a new stack frame is created and pushed onto the top of the stack.
  • A stack frame contains the method's local variables, parameters, and the return address (where to continue execution after the method finishes).
  • When a method completes (i.e., hits a return statement or its closing brace), its stack frame is popped off the top of the stack.
  • Execution resumes at the point indicated by the return address in the new top frame.

Stack Overflow Error: The call stack has a fixed size. If you have too many method calls without returning (a common issue with infinite recursion), the stack will run out of space. This results in a StackOverflowError.

Diagram Description: A diagram showing the call stack. Initially, it contains only the main frame. Then, main calls methodA, so the methodA frame is pushed on top. Then, methodA calls methodB, so the methodB frame is pushed on top. When methodB finishes, its frame is popped. Then methodA finishes, and its frame is popped, leaving only the main frame.

public class StackExample {
    public static void main(String[] args) {
        System.out.println("In main, before calling firstMethod.");
        firstMethod();
        System.out.println("In main, after calling firstMethod.");
    }

    public static void firstMethod() {
        System.out.println("  In firstMethod, before calling secondMethod.");
        secondMethod();
        System.out.println("  In firstMethod, after calling secondMethod.");
    }

    public static void secondMethod() {
        System.out.println("    In secondMethod.");
    }
}

Lesson quiz

What is the most common cause of a `StackOverflowError`?

Next lesson →