Fibonacci Series in Java

Fibonacci series is a sequence of numbers where a number in the sequence is the sum of two previous numbers. By definition, the first two numbers in the series are 0 and 1. The following are the first 12 numbers in the Fibonacci series,

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, .....

Generate Fibonacci Series in Java

The following example program generates and prints Fibaonacci numbers to the console,

/* Finabonacci series example program in Java */
public class Fibonacci {
    
    public static void main(String[] args) {
        generateFibonacci(20);  // generate the first 20 fibonacci numbers
    }
    
    public static void generateFibonacci(long limit) {
        long first = 0;
        long second = 1;
        System.out.print(first+", "+second);
        for(long i=1;i<limit;i++) {
            long next = first + second;
            System.out.print(", "+next);
            first = second;
            second = next;
        }
        System.out.println();
    }
    
}

 

Generate Fibonacci Series in Java Using Recursion

The following example shows how recursion can be used in Java to generate Fibonacci numbers. For large values of limit, the program may run out of stack space.

/* Recursive Fibonacci Series Program in Java */
public class FibonacciRecursion {
    
    public static void main(String[] args) {
        
        long limit = 20;
        for(long i =1; i <=limit;i++) {
            System.out.print(fibonacci(i)+", ");
        }
        
        
    }
    
    public static long fibonacci(long n) {
        if(n<=2) return n-1;
        return fibonacci(n-1)+fibonacci(n-2);
    }
    
}