Java Recursion
Recursion is a technique in Java (and in programming in general) where a method calls itself to solve a problem. In Java, recursion can be used to solve problems that can be broken down into smaller sub-problems that can be solved in a similar way.
A recursive function typically has two parts: the base case and the recursive case. The base case is a condition that, when met, stops the recursion and returns a value. The recursive case is the condition that triggers the method to call itself with a smaller sub-problem.
Here's an example of a recursive function in Java that calculates the factorial of a number:
public static int factorial(int n) { if (n == 0) { return 1; // base case } else { return n * factorial(n-1); // recursive case } }
In this example, the factorial
method takes an integer n
and returns the factorial of n
, which is the product of all positive integers up to n
. If n
is 0, the method returns 1, which is the base case. Otherwise, the method calls itself with the argument n-1
, which is the smaller sub-problem, and multiplies the result by n
, which is the recursive case.