Recursion is a programming technique in which a function calls itself to solve a problem. The function will keep calling itself until a specific base case is reached, at which point the function will stop calling itself and return a final result.
Here's an example of a recursive function in Java that calculates the factorial of a given number:
public static int factorial(int n) { // base case if (n == 0) { return 1; } // recursive case else { return n * factorial(n-1); } }
In this function, the base case is when the input n is equal to zero, in which case the function returns 1. The recursive case is when n is greater than zero, in which case the function calls itself with the input n-1 and multiplies the result by n.
For example, factorial(5) will call factorial(4), which will call factorial(3), and so on, until factorial(0) is called, at which point the base case is reached and the function returns 1. Then, the function returns the final result, which is 5*4*3*2*1 = 120.
Recursion can be a powerful and elegant technique, but it can also be memory-intensive if not used carefully. Therefore, it is important to design the recursion carefully and ensure that the base case will eventually be reached.