Join Peggy Fisher for an in-depth discussion in this video Introducing recursion, part of Learning Java.
- The next topic we're going to review is recursion. Recursion is the process of a method that calls itself to solve a problem. It can call itself again and again to help break down a larger problem to solve it in smaller steps. Let's take a simple example. When we want to print out a countdown from 10 to 1, and then print the word Blast Off! So in this example, we want to stop when the number gets to zero. Let's take a look at the program. If we start with main on line 17, you'll see that, on line 18, is a call to the countdown method with a value of 10 as a parameter.
That value is being passed to the countdown method, into the variable called num. So the first time in the method, I have a value of 10. If num==0, then I'm done, and I'm going to print out the words Blast Off! The first time through, num is not equal to 0, so I go to the else portion of the statement, and I print out the number. So I'm printing out 10. Then, I recursively call the method countdown. It's important to note that you need to make sure you change the value that you're calling the method with, otherwise you'll be in an infinite loop.
You can see here, I'm calling it after I subtract 1 from the value. So 10 - 1 is 9. I go back up to line 20 and I start all over again. I come back in, num is still not equal to 0 because it's 9, I print out 9, and I call countdown again. This continues until num does get down to 0. When num is 0, it says if num==0, print out the word Blast Off! Note that in the if part of the statement, I don't call the countdown method again.
So once it gets to 0, my program ends. Let's run this so we can see what it looks like. I scroll up, it starts at 10. It goes all the way down to 1, and then prints out the word Blast Off! This is just one example of recursion. In any recursive problem, it's really important to figure out what constitutes the end of my process. This is what we call the base case, and without it, we would have an infinite loop, because the method would constantly call itself with no end.
Very easily, I could change this to take out the num - 1 and just make it num, and I would have an infinite loop. Note that you never have to actually use recursion in programming. Many of the recursive processes can be done using a loop, but there are times when it can be more efficient.
- Downloading and exploring NetBeans
- Understanding Java basics: data types, strings, arrays, and more
- Controlling flow with functions and loops
- Creating classes
- Sorting and searching arrays
- Manipulating files
- Handling errors
- Building GUIs