Title here
Summary here
Our example demonstrates recursion in Java. Here’s the implementation:
public class Recursion {
// This fact function 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 for recursive functions
// We need to declare the type explicitly to use recursion
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 fact
function calls itself until it reaches the base case of fact(0)
.
In Java, we can use lambda expressions or anonymous inner classes for recursive functions. However, due to limitations with recursive lambdas in Java, we use an anonymous inner class implementing IntUnaryOperator
for the Fibonacci function.
Since fib
is declared as an IntUnaryOperator
, Java knows which function to call with fib
here.
To run the program, compile it and then use java
:
$ javac Recursion.java
$ java Recursion
5040
13
This example demonstrates how recursion works in Java, both with regular methods and with functional interfaces.