Recursion in Java

Recursion in Java

 

Here, in this page we will discuss about recursion in java. Recursion is the technique of making a function call itself. A method in java that calls itself is called recursive method.
Recursion makes the code compact but it is complex to understand that code. All problems that are solved using recursion can also be solved using iterations. Recursion is made for solving problems that can be broken down into smaller, repetitive problems.

Recursion in Java

Why Recursion?

  • Recursion involves calling the same function again, and hence, has a very small length of code.
  • It is especially good for working on things that have many possible branches and are too complex for an iterative approach.
  • Recursion is best suited in trees and graphs problems.

 

Halting Condition

  • Just as loops can run into the problem of infinite looping, recursive functions can run into the problem of infinite recursion.
  • Infinite recursion is when the function never stops calling itself.
  • Every recursive function should have a halting condition, which is the condition where the function stops calling itself.

 

Why Stack Overflow error occurs in recursion in java ? 

If the base case is not reached or not defined, then the stack overflow problem may arise.

Let’s discuss the program to find the sum of n numbers using recursion. To understand recursion properly.

 

Algorithm :

  • Create a Recursive function say Sum(int n).
  • If( n<=1 ) , then return n
  • Otherwise Return n + Sum(n-1).
Recursion

Code to find Sum of n Numbers using Recursion in Java

import java.util.*;
import java.lang.*;

class Main
{
   public static int Sum(int n)
   {
     if (n <= 1) //Halting Condition
     return n;
     return n + Sum(n - 1);
   }

   // Driver code
   public static void main(String args[])
   {
      int n = 5;
      System.out.println(Sum(n));
   }
}
Output :
15

Advantages of Recursion in Java

  • It makes the length of code shorter.
  • Makes code more cleaner.
  • It is especially good for working on things that have many possible branches and are too complex for an iterative approach.
  • Recursion is best suited in trees and graphs problems.

 

Disadvantages of Recursion in Java

  • Recursive programs takes a lot of stack space compared to an iterative program.
  • They uses more processor time.
  • It is more difficult to debug a recursive code as compared to an equivalent iterative program.