Site icon DataFlair

Recursion in Java – Working, Advantages and Disadvantages

recursion in java

Get Job-ready: Java Course with 45+ 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:

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 the 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 the 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); 

}

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.

Recursion uses the Stack for assigning the memory; it means the first function call is stacked at the bottom, and the last function call is placed at the top.

Example of recursion in Java:

public static void print(int n){

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

  print(n - 1);

}

print(3);

The memory allocation happens like:

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:

Disadvantages of Recursive Programming

Some drawbacks of using recursion:

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.

Exit mobile version