rancho rancho - 3 months ago 11
Java Question

Is it possible to print Fibonacci series in java without using recursion, loop and custom function

I have been trying various methods. However I cannot find out whether it is possible to print Fibonacci series in java without using recursion, loop and custom functions. If yes then how?

Answer

You can use the scheduled exector pool. It's not technically a loop, though it is using the repeating thread to behave like a loop.

private static volatile int currentNum = 1;
private static volatile int previousNum = 0;

public static void main(String[] args) {
    ScheduledThreadPoolExecutor timer = new ScheduledThreadPoolExecutor(1);
    timer.scheduleWithFixedDelay(() -> {
        System.out.println(currentNum);
        int temp = currentNum;
        currentNum += previousNum;
        if (currentNum < 0) {
            // overflow
            timer.shutdown();
        }
        previousNum = temp;
    }, 0, 1, TimeUnit.MILLISECONDS);
}
Comments