Recursion in Java
Recursion is a programming technique where a method calls itself to solve smaller instances of a problem. This approach is particularly useful for problems that can be divided into similar sub-problems, such as mathematical computations, data structure traversal, and more.
A recursive function has two main components:
StackOverflowError.The factorial of a number $$ n $$ is defined as $$ n! = n \times (n-1)! $$, with $$ 0! = 1 $$.
class Factorial {
static int factorial(int n) {
// Base case
if (n == 0) {
return 1;
}
// Recursive case
return n * factorial(n - 1);
}
public static void main(String[] args) {
int number = 5;
System.out.println("Factorial of " + number + " is: " + factorial(number));
}
}
Output:
Factorial of 5 is: 120