18.6 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 and stack frames. In this section, we’ll 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. 18.6. To show the order in which the method calls’ stack frames are placed on the stack, we’ve lettered the method calls in Fig. 18.7.

Image

Fig. 18.7 | Method calls made within the call fibonacci(3) ...

Get Java™ How To Program (Early Objects), Tenth 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.