Recursion in Java
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:
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.