Java Fibonacci Program

Introduction

The Fibonacci Series is one of the most popular programming examples for beginners learning Java. It consists of a sequence of numbers where each number is the sum of the two preceding numbers.

The Fibonacci sequence starts with:


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

Here’s how the sequence is generated:

  • First number = 0
  • Second number = 1
  • Third number = 0 + 1 = 1
  • Fourth number = 1 + 1 = 2
  • Fifth number = 1 + 2 = 3
  • Sixth number = 2 + 3 = 5

The formula for the Fibonacci sequence is:


F(n) = F(n-1) + F(n-2)

The Fibonacci program is commonly asked in Java interviews because it helps evaluate a candidate’s understanding of loops, recursion, variables, and mathematical logic.

In this tutorial, you’ll learn different ways to generate the Fibonacci series in Java.

Java Program to Print Fibonacci Series Using a Loop


public class Fibonacci {
    public static void main(String[] args) {
        int n = 10;
        int first = 0;
        int second = 1;
        System.out.print("Fibonacci Series: ");
        for (int i = 1; i <= n; i++) {
            System.out.print(first + " ");
            int next = first + second;
            first = second;
            second = next;
        }
    }
}

Output

Fibonacci Series: 0 1 1 2 3 5 8 13 21 34

How the Program Works?

Let's understand the logic step by step.

Step 1: Initialize Variables


int first = 0;
int second = 1;

These represent the first two numbers of the Fibonacci series.

Step 2: Run the Loop


for (int i = 1; i <= n; i++)

The loop executes n times.

Step 3: Print the Current Number


System.out.print(first + " ");

The current Fibonacci number is printed.

Step 4: Calculate the Next Number


int next = first + second;

The next Fibonacci number is the sum of the previous two numbers.

Step 5: Update the Variables


first = second;
second = next;

The values move forward for the next iteration.

Java Program Using User Input


import java.util.Scanner;
public class Fibonacci {
    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 first = 0;
        int second = 1;
        System.out.print("Fibonacci Series: ");
        for (int i = 1; i <= n; i++) {
            System.out.print(first + " ");
            int next = first + second;
            first = second;
            second = next;
        }
        scanner.close();
    }
}

Output

Enter the number of terms: 8
Fibonacci Series: 0 1 1 2 3 5 8 13

Java Fibonacci Program Using Recursion

Another way to generate Fibonacci numbers is by using recursion.


public class Fibonacci {
    static int fibonacci(int n) {
        if (n <= 1)
            return n;
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
    public static void main(String[] args) {
        int n = 10;
        for (int i = 0; i < n; i++) {
            System.out.print(fibonacci(i) + " ");
        }
    }
}

Output

0 1 1 2 3 5 8 13 21 34

Note: Although recursion is easy to understand, it is less efficient for larger values of n because it performs many repeated calculations.

Java Program to Find the Nth Fibonacci Number


public class Fibonacci {
    public static void main(String[] args) {
        int n = 10;
        int first = 0;
        int second = 1;
        if (n == 0) {
            System.out.println(first);
            return;
        }
        for (int i = 2; i <= n; i++) {
            int next = first + second;
            first = second;
            second = next;
        }
        System.out.println("Nth Fibonacci Number = " + second);
    }
}

Output

Nth Fibonacci Number = 55

Algorithm

  1. Read the number of terms.
  2. Initialize the first two Fibonacci numbers as 0 and 1.
  3. Print the first number.
  4. Calculate the next number by adding the previous two numbers.
  5. Update the variables.
  6. Repeat until all terms are printed.

Flowchart Logic


 Start
   │
Read Number of Terms
   │
Initialize first = 0, second = 1
   │
Print first
   │
Calculate next = first + second
   │
Update first and second
   │
More Terms?
   │
  Yes ───► Repeat
   │
  No
   │
  End

Time Complexity

Using Loop


O(n)

The loop executes exactly n times.

Using Recursion


O(2ⁿ)

The recursive solution recalculates many values, making it inefficient for large inputs.

Space Complexity

Loop Approach


O(1)

Only a few variables are used.

Recursive Approach


O(n)

Recursive function calls consume stack memory.

Common Mistakes

1. Incorrect Variable Updates

Incorrect:


first = next;
second = first;

Correct:


first = second;
second = next;

2. Forgetting to Store the Next Value

Incorrect:


first = second;
second = first + second;

Correct:


int next = first + second;
first = second;
second = next;

3. Wrong Loop Condition

Incorrect:


for(int i = 0; i <= n; i++)

This may print one extra term depending on the implementation.

Correct:


for(int i = 1; i <= n; i++)

or


for(int i = 0; i < n; i++)

depending on the logic used.

4. Missing Base Case in Recursion

Incorrect:


return fibonacci(n - 1) + fibonacci(n - 2);

Without a base case, the recursion never stops.

Correct:


if (n <= 1)
    return n;

5. Using int for Very Large Fibonacci Numbers

For larger values of n, int can overflow. Use long or BigInteger if you need to generate very large Fibonacci numbers.

Applications of Fibonacci Series

The Fibonacci sequence has practical applications in many fields, including:

  • Computer algorithms
  • Dynamic programming
  • Data structures
  • Mathematics
  • Financial analysis
  • Nature and biology (leaf arrangements, flowers, shells)
  • Graphics and animation
  • Cryptography

Summary

The Java Fibonacci program is one of the most important beginner-level programming examples. It teaches fundamental programming concepts such as loops, recursion, variables, methods, and arithmetic operations.

For most practical applications, the iterative approach is preferred because it runs in O(n) time with O(1) space. The recursive approach is useful for learning recursion but is inefficient for large values unless combined with techniques like memoization or dynamic programming.

Related Java Tutorials