Recursion in Java

Recursion in Java

Recursion in Java

Recursion in Java:

Recursion is a programming technique that involves a function calling itself. In Java, recursion can be used to solve problems that can be broken down into smaller, simpler versions of themselves.

Here’s an example of a simple recursive function in Java that calculates the factorial of a given number:

				
					public static int factorial(int n) {
   if (n == 0) {
      return 1;
   } else {
      return n * factorial(n-1);
   }
}

				
			

In this example, the factorial() function calls itself with a smaller input value (n-1) until it reaches the base case of n=0, at which point it returns 1.

Another example of a recursive function in Java is one that calculates the nth Fibonacci number:

				
					public static int fibonacci(int n) {
   if (n <= 1) {
      return n;
   } else {
      return fibonacci(n-1) + fibonacci(n-2);
   }
}

				
			

In this example, the fibonacci() function calls itself twice with smaller input values (n-1 and n-2) until it reaches the base case of n=0 or n=1, at which point it returns the value of n.

It’s important to note that recursive functions can be less efficient than iterative (loop-based) functions, particularly for large input values, because of the added overhead of function calls and stack space used to maintain the call stack.

 

 

Join To Get Our Newsletter
Spread the love