Recursion in Java – Working, Advantages and Disadvantages

Free Java courses with 37 real-time projects - Learn Java

Recursion refers to a programming technique where a function calls itself repeatedly to solve a problem. In Java, a method that calls itself is known as a recursive method. The method breaks down a problem into smaller sub-problems and continues to call itself to get the solution.

Some key points about recursive functions in Java:

  • A recursive function has a base case and a recursive case. The base case is the termination condition that allows the function to stop calling itself.
  • Recursion is best applied to problems that can be divided into smaller repetitive sub-problems. Some examples are calculating factorials, generating Fibonacci series, traversing tree data structures, etc.
  • Recursion provides an elegant and simple solution to certain complex problems that are difficult to solve iteratively.

Base Condition in Recursion

The base condition in recursion specifies the termination point where the recursive calls will end. Without a base condition, a recursive function will go into an infinite loop.

For example, consider a recursive function to calculate factorials:

public static int factorial(int n){
  if(n <= 1){ //base case
    return 1; 
  }
  else{
    return n * factorial(n-1); //recursive call
  }
}

Here, the base case is defined as n <= 1. For n = 0 or n = 1, the function will return 1 and not make any further recursive calls.

For larger values of n, the factorial is calculated by calling factorial(n-1) recursively and multiplying it with n. The multiplication happens after the recursive call returns the factorial value for (n-1).

Defining an appropriate base condition is critical in recursive programming to prevent infinite recursions.

Working on Recursion in Java

The fundamental idea behind recursion is representing a problem in terms of itself. A recursive function calls itself to solve smaller instances of the same problem.

The base case acts as the termination condition for recursion. It breaks down a large problem into successively smaller sub-problems, and the function keeps calling itself recursively until it reaches the base case.

For example, to calculate a factorial of 5:

public static int factorial(int n){
  
  if(n <= 1){ //base case
    return 1;
  }
  
  else {
    return n * factorial(n-1); //recursive call
  }

}


//Calculating factorial(5)
factorial(5) 
   = 5 * factorial(4) 
      = 5 * (4 * factorial(3))
         = 5 * (4 * (3 * factorial(2))) 
            = 5 * (4 * (3 * (2 * factorial(1))))
               = 5 * (4 * (3 * (2 * 1))) 
                  = 120

As we can see, the larger problem is broken down into successively smaller sub-problems using the recursive calls until the base case is reached.

Another example is Fibonacci series where each term is the sum of the previous two terms:

public static int fibonacci(int n){

  if(n <= 1){ 
    return n;
  }

  return fibonacci(n-1) + fibonacci(n-2); 

}

working of recursion

Memory Allocation in Java Recursion

When a function calls itself recursively, a new function invocation is placed on top of the call stack. All local variables and parameters are allocated separately for each invocation.

For example:

public static void print(int n){

  if(n < 1) 
    return;
  
  System.out.print(n + " ");

  print(n - 1);

}

print(3);

The memory allocation happens like:

  • print(3) is called, n = 3
  • print(2) is called, a new n = 2
  • print(1) is called, a new n = 1
  • print(0) returns back without calling since n < 1

Output:
3 2 1

Each recursive call has its own n value allocated separately on the stack.

Advantages of Recursive Programming

Some benefits of using recursive functions:

  • Simpler and clean code: Recursive solutions are often elegant, easy to code, and avoid complex iterative logic.
  • Ideal for nested and hierarchical problems: Problems involving traversal of tree structures, nested iterations lend themselves well to recursive solutions.

Disadvantages of Recursive Programming

Some drawbacks of using recursion:

  • Memory overhead: Due to function stack additions, recursive code requires more memory than iterative solutions.
  • Slower performance: Recursive calls are generally costlier than iterative loops due to overhead of function calls.

However, optimized compilers can convert some types of recursion (tail recursion) into iterations for better performance. Also, both recursive and iterative solutions have polynomial time complexity.

Conclusion

Recursion is a powerful programming technique where a function calls itself to solve smaller instances of a problem. When applied properly, recursion can simplify solutions to complex problems involving nested structures or divide-and-conquer strategies. However, recursion also has drawbacks like high memory usage and slower performance compared to iteration.

Overall, recursion allows elegant code for certain problems but should be used judiciously after understanding both its advantages and disadvantages. The choice between recursive and iterative solutions depends on the problem, data structures, and performance requirements.

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

follow dataflair on YouTube

Leave a Reply

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