# Recursion in Java | Recursive Methods with Program Examples

Recursion in Java is a process in which a method calls itself continuously. Using recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc.  A method in java that calls itself is called recursive method.

##### Working of Recursive Methods –
• In the above program, recursiveMethod() method is called from inside the main method at first (normal method call).
• Also, recursiveMethod() method is called from inside the same method, recursiveMethod(). This is a recursive call.
• The recursion continues until some condition is met to prevent it from execution. If not, infinite recursion occurs.
• Hence, to prevent infinite recursion, if…else statement (or similar approach) can be used where one branch makes the recursive call and other doesn’t.
##### Recursive Program example to Find Factorial of a Number –

Output
Factorial of 4 is 24

Let us see a visual diagram to understand the working of the above mentioned program –

As you can see in the above diagram, the fact() function is recursively called 4 times till the value of n becomes 1. Once the value of n becomes 1, the appropriate values are being returned i.e. value 1 is returned from the last function call, value 2 is returned from second last function call, value 12 is returned from third last function call and finally value 24 is returned from the first function call which is then directly printed on the console.