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.

How does Recursion work in Java ?

recursive method in java

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 –

Run Online

Output
Factorial of 4 is 24

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

recursion in java example working

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.

Advantages & Disadvantages of Recursion and Recursive Methods –
  • Advantage : The main advantage of recursion is that for problems like tree traversal it make the algorithm a little easier or more “elegant”.
  • Disadvantage : When a recursive call is made, new storage location for variables are allocated on the stack. As, each recursive call returns, the old variables and parameters are removed from the stack. Hence, recursion generally use more memory and are generally slow.

Leave a Reply

Your email address will not be published. Required fields are marked *