Hello team!
In this lesson we will learn what are recursive methods and how to use them.
What is recursion?
Recursion is a process in which a method calls itself continuously.
A method in Java that calls itself is called recursive method.
Let's write the easiest recursive method.
I have the method which calls itself, and when it calls itself, it calls the same method again.
This is recursive method.
What is wrong here?
Let's run our program.
We have stack overflow error.
Why this has happened?
Because when a recursive call is made, new storage locations for variables are located in the stack
memory of the JVM.
So each recursive call will add a new frame to the stack.
That means we can run out of memory, because information about initial and other method invocations
won't be removed from the stack.
We need to finish method to release memory in stack.
But when we call the same method again and again, it just can't be completed.
So here is an important rule which you have to always keep in mind.
When you create recursive methods, you should clearly define stop condition.
The condition when recursion must be stopped and value should be returned.
Let's find factorial of a number.
Factorial of a positive integer is a result of multiplication Application of all positive integers less
than or equal to original number.
We'll write recursive method in case I is not equal to zero.
Then we can multiply I by the result of the same method, but with number decreased by one, and when
I will be equal to zero, we return one and no recursion here anymore.
We broke the chain of recursion calls.
Let me comment this method first.
Now I can run the program again and you see the result in console.
Here we calculated factorial of three and four.
Now when you know how recursive method works, let's recap.
Pros and cons of recursive methods.
Recursive methods usually look clean and easy to understand.
Often we can achieve our goal without recursive methods.
For example, here is the same method to calculate factorial but without recursion, and you see that
it is a bit longer and less clear than recursive one.
So clean design is an advantage of recursive methods, but recursive methods have one huge drawback.
In case there will be a lot of methods, invocations or stop condition will be written incorrectly.
Your program will be stopped because of stack overflow error.
Now you know pros and cons of recursive methods.
I will share with you coding exercises to write recursive methods.
Thanks a lot for your attention.
See you in the next lesson.
Your.