15.5. Recursion and the Method-Call Stack

In Chapter 6, the stack data structure was introduced in the context of understanding how Java performs method calls. We discussed both the method-call stack (also known as the program execution stack) and activation records. In this section, we will use these concepts to demonstrate how the program execution stack handles recursive method calls.

Let’s begin by returning to the Fibonacci example—specifically, calling method fibonacci with the value 3, as in Fig. 15.7. To show the order in which the method calls’ activation records are placed on the stack, we have lettered the method calls in Fig. 15.8.

Figure 15.8. Method calls made within the call fibonacci(3).

When the first method call (A) is ...

Get Java™ How to Program, Seventh Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.