Java Java Tutorial Java Methods Java Classes Java File Handling Java Reference



Java Recursion

Recursion is a programming technique in which a function calls itself repeatedly until a certain condition is met. In Java, recursion is a powerful tool that can be used to solve complex problems in an elegant and efficient way.

Recursion is based on the principle of divide and conquer. The problem is divided into smaller sub-problems, and each sub-problem is solved recursively. The solution to the original problem is then obtained by combining the solutions to the sub-problems.

Recursion can be used to solve a wide range of problems, including searching, sorting, and traversing data structures such as trees and graphs. It is also used in many mathematical algorithms, such as the Fibonacci sequence and the factorial function.

Example of Java Recursion

Let's take a look at a simple example of recursion in Java. The following code calculates the factorial of a given number:


public class Factorial {
    public static int factorial(int n) {
        if (n == 0) {
            return 1;
        } else {
            return n * factorial(n - 1);
        }
    }
    
    public static void main(String[] args) {
        int n = 5;
        int result = factorial(n);
        System.out.println("The factorial of " + n + " is " + result);
    }
}

In this example, the factorial() method calls itself recursively until the base case is reached (when n equals 0). The base case is the simplest case that can be solved without recursion. In this case, the base case is when n equals 0, and the factorial of 0 is 1.

The code then returns the product of n and the factorial of n-1. This process continues until the base case is reached, at which point the final result is returned.

When we run this code, we get the following output:

The factorial of 5 is 120

This is because 5! (5 factorial) equals 120.

Conclusion

Recursion is a powerful programming technique that can be used to solve complex problems in an elegant and efficient way. It is based on the principle of divide and conquer, and can be used to solve a wide range of problems in Java.

References

Activity