Logout

Method Call Stacking


(Refer also to "Recursion Analogies".)


Method Calling Stacking Analogy

The idea here is that one method can call another, which can call another, and so on. But no method can finish, and therefore be garbage collected from memory until the methods that it calls are finished. These unfinished methods are usually stacked up as they are called, with the most recent being on the top of the stack, and the initial (usually, ultimately the main method) being on the bottom of the stack. And usually the methods are attended to in a LIFO (Last in First Out) fashion. Here's an example of how I might be interrupted by calls to my attention in class.

"So, I'll get back to taking about loops after I mention something quickly about..."

(There's a knock at the door.) "Just a minute, I'll see who's at the door".

(Just then, my mobile phone goes off.) "Woops... it's my my phone; I had better answer it; I'll be right with you."

"Yes, this is John Rayworth. Yes, I subscribe to O2..." (Then my desk phone starts to ring.) "Just one minute... my other phone is ringing."

"Oh, hello, Veronika, yes, Adam is here. Ok, I'll get him to go sign in."

 

So at this point there is a stack of five things I'm in the process of doing. I'll finish them one at a time, starting with the last one "in" on the stack.

 

Ok, bye. Have a good day, Veronika.

(Back to the mobile phone.) Sorry, what were you saying? No, no, thanks; I like my service the way it is. Good bye..

(Back to the visitor at the door.) Would you just like to print? That's ok; go ahead.

(Back to teaching.) So, as I was saying the thing that I wanted to mention quickly was...

And now back to loops...

 

Here's an actual unfinished method calls example:

public static void main String[] args{
    method1();
}

public static void method1();
method2();
} public static void method2(){ method3(); }

public static void method3(){ System.out.println("Finally, we're getting some place!"); }

Main calls method1, which calls method2, which calls method3. When we get into method 3, all four methods are in memory, all waiting to complete. So the stack, with the most recent calls on the top is: (Note that the diagrams in Morelli go the reverse way.)

method3
method2
method1
main

They get "popped" off the top of the stack (just like a PEZ candy - see image below) one at a time as they are completed, starting with method3 and working down to main.