Recursion in Java

import java.util.function.IntUnaryOperator;

public class Recursion {

    // This `fact` method calls itself until it reaches the
    // base case of `fact(0)`.
    public static int fact(int n) {
        if (n == 0) {
            return 1;
        }
        return n * fact(n - 1);
    }

    public static void main(String[] args) {
        System.out.println(fact(7));

        // In Java, we can use lambda expressions to create recursive functions.
        // However, we need to use a wrapper class to allow self-reference.
        IntUnaryOperator fib = new IntUnaryOperator() {
            @Override
            public int applyAsInt(int n) {
                if (n < 2) {
                    return n;
                }
                return applyAsInt(n - 1) + applyAsInt(n - 2);
            }
        };

        System.out.println(fib.applyAsInt(7));
    }
}

This Java code demonstrates recursion, which is a technique where a function calls itself to solve a problem.

The fact method is a classic example of recursion, calculating the factorial of a given number. It calls itself with a decremented value until it reaches the base case of 0.

In the main method, we first call fact(7) to calculate 7 factorial and print the result.

Java doesn’t have direct support for recursive closures like some other languages. However, we can achieve similar functionality using lambda expressions and functional interfaces. In this example, we use IntUnaryOperator to create a recursive Fibonacci function.

The Fibonacci function is defined as an anonymous class implementing IntUnaryOperator. It checks for the base cases (n < 2) and then recursively calls itself for larger values.

Finally, we call the Fibonacci function with an input of 7 and print the result.

To run this program, save it as Recursion.java, compile it, and then run it:

$ javac Recursion.java
$ java Recursion
5040
13

The output shows the factorial of 7 (5040) and the 7th Fibonacci number (13).

This example demonstrates how recursion can be implemented in Java, both with regular methods and with functional interfaces.