Print Fibonacci Series in Java Using Different Methods

The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. The series looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on. In this article, we will explore various methods to generate and print the Fibonacci series in Java.

Method 1. Using Iteration in Java

The iterative approach uses loops to calculate the Fibonacci numbers. This method is efficient and easy to understand.

import java.util.Scanner;

public class FibonacciIterative {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number of terms: ");
        int n = scanner.nextInt();

        int firstTerm = 0, secondTerm = 1;
        System.out.println("Fibonacci Series up to " + n + " terms:");

        for (int i = 1; i <= n; i++) {
            System.out.print(firstTerm + ", ");
            int nextTerm = firstTerm + secondTerm;
            firstTerm = secondTerm;
            secondTerm = nextTerm;
        }

        scanner.close();
    }
}

Explanation

  • We take the number of terms as input from the user.
  • We use a for loop to iterate through the number of terms and print each term.
  • The next term is calculated by summing the previous two terms.

Output

Fibonacci Iterative in Java

Method 2. Using Recursion in Java

The recursive approach involves a function that calls itself to calculate Fibonacci numbers. This method is elegant but can be inefficient for large inputs due to repeated calculations.

Code Example

import java.util.Scanner;

public class FibonacciRecursive {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number of terms: ");
        int n = scanner.nextInt();

        System.out.println("Fibonacci Series up to " + n + " terms:");
        for (int i = 0; i < n; i++) {
            System.out.print(fibonacci(i) + ", ");
        }

        scanner.close();
    }

    public static int fibonacci(int n) {
        if (n == 0) return 0;
        if (n == 1) return 1;
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
}

Explanation

  • The Fibonacci method calculates the nth Fibonacci number using recursion.
  • The main method iterates through the number of terms and prints each Fibonacci number by calling fibonacci(i).

Output

Fibonacci Resursive

Method 3. Using Dynamic Programming (Memoization) in Java

To optimize the recursive approach and avoid repeated calculations, we can use memoization. This technique stores previously computed values.

Code Example

import java.util.HashMap;
import java.util.Scanner;

public class FibonacciMemoization {
    private static HashMap<Integer, Integer> memo = new HashMap<>();

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number of terms: ");
        int n = scanner.nextInt();

        System.out.println("Fibonacci Series up to " + n + " terms:");
        for (int i = 0; i < n; i++) {
            System.out.print(fibonacci(i) + ", ");
        }

        scanner.close();
    }

    public static int fibonacci(int n) {
        if (n == 0) return 0;
        if (n == 1) return 1;
        
        // Check if value is already computed
        if (memo.containsKey(n)) {
            return memo.get(n);
        }

        // Compute and store in memo
        int result = fibonacci(n - 1) + fibonacci(n - 2);
        memo.put(n, result);
        
        return result;
    }
}

Explanation

  • We use a HashMap to store previously computed Fibonacci numbers.
  • Before calculating a Fibonacci number recursively, we check if it exists in the memo. If it does, we return it directly.

Output Example

Fibonacci Memoization

Method 4. Using Streams in Java

Java Streams provide a modern way to generate sequences. You can use streams to produce the Fibonacci series in a functional style.

Code Example

import java.util.stream.Stream;

public class FibonacciStream {
    public static void main(String[] args) {
        int n = 10; // Number of terms

        System.out.println("Fibonacci Series up to " + n + " terms:");
        
        Stream.iterate(new int[]{0, 1}, f -> new int[]{f[1], f[0] + f[1]})
              .limit(n)
              .forEach(f -> System.out.print(f[0] + ", "));
    }
}

Explanation

  • We use Stream. iterate to create an infinite stream of Fibonacci pairs.
  • Each pair consists of two integers representing consecutive Fibonacci numbers.
  • We limit the stream to n elements and print each one.

Output

Fibonacci Stream

Conclusion

In this article, we explored different methods for generating and printing the Fibonacci series in Java. From iterative and recursive approaches to dynamic programming and modern streams in Java's functional programming paradigm, each method has its advantages depending on the context in which it is used. By understanding these techniques thoroughly, you can choose the best approach that suits your needs for generating Fibonacci numbers in your applications.