Recursion in Logo
This Java code demonstrates recursion, a concept where a function calls itself. Here’s a breakdown of the example:
We define a static method
fact
that calculates the factorial of a number recursively. It calls itself withn-1
until it reaches the base case of 0.In the
main
method, we first call and print the result offact(7)
.Java doesn’t have closures in the same way as some other languages, but we can achieve similar functionality using lambda expressions or anonymous inner classes. In this example, we use an anonymous inner class that implements
IntUnaryOperator
to create a recursive Fibonacci function.The Fibonacci function is defined to return
n
ifn
is less than 2, otherwise it returns the sum offib(n-1)
andfib(n-2)
.Finally, we call the Fibonacci function with
fib.applyAsInt(7)
and print the result.
To run this program, save it as Recursion.java
, compile it with javac Recursion.java
, and then run it with java Recursion
. The output will be:
This example demonstrates how recursion can be implemented in Java, both with regular methods and with functional interfaces. While Java doesn’t have the exact same syntax for closures as some other languages, it provides powerful alternatives that allow for similar patterns of recursive computation.