Fibonacci Series in Java

Fibonacci Series in Java

Ever thought about how to generate the Fibonacci numbers using Java? What are the different ways to print the Fibonacci numbers in Java? Should you use loops, recursion, or dynamic programming, and which method is the fastest? Can you take input from the user to control how many numbers to print? In this guide, we will answer all these questions and show clear examples to help you learn easily.

Table of Contents:

What is the Fibonacci Series in Java?

The Fibonacci series in Java is a sequence of numbers where each number is the sum of the previous two numbers. The series starts mainly with 0 and 1, and from there, each next number is formed by adding the two numbers that are before it.

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

In the above example,

0+1=1
1+1=2
2+1=3
3+2=5
5+3=8
8+5=13

and so on.

The Fibonacci series in Java can be performed in many ways. Some of the ways are discussed below.

Master Java Today - Accelerate Your Future
Enroll Now and Transform Your Future
quiz-icon

Fibonacci Series Using the Iterative Approach

Fibonacci Series Using the Iterative Approach is the easiest and simplest approach. It uses a for or while loop to calculate the next number in the sequence.

1. Using a for loop

This way is useful when you use a for loop, and when you know how many terms you want to generate in the Fibonacci series.

Syntax:

for (initialization; condition; update) {
    // body of the loop
}

Example:

Java

Output:

Using a for loop

Explanation: In the above Java code, the number of terms to be printed is 7. The first and the second numbers were the Fibonacci series, which are 0 and 1. The for loop starts from i=2, because 0 and 1 are already printed, next = first + second, and then the first = second, second = next.

2. Using a While Loop

The while loop is used when you want to generate Fibonacci numbers until a certain value is reached, not a fixed count.

Syntax:

while (condition) {
    // loop body (code to execute repeatedly)
}

Example:

Java

Output:

Using a While Loop

Explanation: In the above Java code, the while loop will generate a Fibonacci series of till the numbers are less than or equal to 20. The first and second are initialized as 0 and 1. The while loop calculates the next number, and then shifts the numbers.

3. Using a do-while Loop

A do-while loop is used when you want to execute the Fibonacci series at least once, and want to continue further based on a condition.

Syntax:

do {
    // loop body
} while (condition);

Example:

Java

Output:

Using a do-while Loop

Explanation: In the above Java code, the do block runs first, before checking the condition in the while block. It prints the Fibonacci numbers until the current number (first) becomes greater than 50, not the next number.

Get 100% Hike!

Master Most in Demand Skills Now!

Fibonacci Series Using a Method

The Fibonacci Series can also be printed by using a Method, i.e., creating a reusable method that calculates and prints the Fibonacci sequence, and then using iteration, like a for or while loop.

Example:

Java

Output:

Fibonacci Series Using a Function

Explanation: In the above Java code, the printFibonacci(int n) is a method that displays the first n Fibonacci numbers. After that, the loop is used, which runs n times, printing the current number and updating values.

Fibonacci Series Using Recursion

Recursion is a technique where a method calls itself until the base condition is met. It solves the smaller versions of the problem. Recursion is very useful in problems that can be defined in terms of repeated sub-problems, like the Fibonacci series.

For the Fibonacci series, the recursion is achieved by the following condition,

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

Where F(n) is the method and n is the index in the Fibonacci sequence.

Example:

Java

Output:

Fibonacci Series Using Recursion

Explanation:

  • The fib method is a recursive function that calculates the nth Fibonacci number.
  • If n is 0 or 1, it returns n directly (base case).
  • Otherwise, it calls itself recursively with n-1 and n-2 and adds the results.

In the main method:

  • We set n = 10 to define how many Fibonacci terms to print.
  • A for loop iterates from 0 to n-1, printing each Fibonacci number by calling fib(i).

The output is the Fibonacci sequence up to 10 terms.

Fibonacci Series Using Recursion in Java

In the above image,

F(5) = F(4) + F(3)

= (F(3) + F(2)) + (F(2) + F(1))

= ((F(2) + F(1)) + (F(1) + F(0))) + ((F(1) + F(0)) + F(1))

Note: The method F(n) is calculated until it reaches the base cases where n is 0 or 1.

Fibonacci Series Using Memoization

Memoization is a method in which the results of repeated method calls are stored and reused later, when the same inputs occur again and again. It avoids repetitive calculations and improves performance in recursive problems like Fibonacci.

In the process of recursion, the F(n) having the same value of n is repeated many times, such as F(3) and F(4), which leads to the overlapping of the subproblems and increasing time complexity. Memoization stores the calculated Fibonacci numbers in an array or a HashMap and reuses them later when needed.

Example:

Java

Output:

Fibonacci Series Using Memoization

Explanation: In the above Java program, the memo[] stores the previously computed Fibonacci numbers, and before finding any Fibonacci (n) value, we check if the value already exists in memo[n]. The memo[ ] array is initialized with -1 to indicate no value is stored in it.

Fibonacci Series Using Dynamic Programming

Dynamic Programming is a method in which problems are broken into smaller subproblems, and each subproblem is solved only once, and the result is stored to avoid repetitive work.

There are two main ways to do this:

  • Top-Down approach (with recursion + memoization)
  • Bottom-Up approach (with iteration)

Among the top-down and bottom-up approaches, the Bottom-Up Dynamic programming is more efficient and avoids recursion. Now, further below, we use Bottom-Up Dynamic Programming as it is more efficient.

Example:

Java

Output:

Fibonacci Series Using Dynamic Programming

Explanation: In the above Java program, the fib[ ] is an array that stores the Fibonacci numbers from F(0) to F(n). The first two elements, F(0) and F(1), are set initially, then the for loop fills in the rest, i.e., F(i) = F(i-1) + F(i-2), and finally, we print the first n Fibonacci numbers.

Fibonacci Series Up to a Given Number Using the Scanner

It prints all the Fibonacci numbers that are less than or equal to a given number, which the user has given the input n. It starts with 0 and 1 as the first two terms, and then calculates the next term as the sum of the previous two. This process is continued until the current term is less than or equal to the given number n.

Example:

Java

Output:

Fibonacci Series Up to a Given Number Using the Scanner

Explanation: In the above Java code, first, the input is taken from the user through the Scanner class, then a while loop continues as long as the condition ≤ max is true. Then it prints each Fibonacci number until it exceeds the user-given number.

Note: If the user enters a negative number, it will print nothing.

Performance Comparison of Different Methods

MethodTime NeededMemory UsedSpeed
IterativeO(n)O(1)Fast
Method with LoopO(n)O(1)Fast
RecursionO(2ⁿ)O(n)Very Slow
MemoizationO(n)O(n)Very Fast
Dynamic Programming (Bottom-Up)O(n)O(n)Very Fast
Up to a Given NumberO(n)O(1)Fast
Unlock Your Future in Java
Start Your Java Journey for Free Today
quiz-icon

Conclusion

From the above article, we conclude that there are many ways to print the Fibonacci series in Java. If you want a quick and easy method, using loops or methods is best. Recursion shows how the series works, but it is slow. Memoization and dynamic programming make it faster by saving the work that has already been done. And, if you want to take input from the user, the Scanner method is helpful.

If you want to learn more about this topic, you can refer to our Java course.

Fibonacci Series in Java – FAQs

Q1. What is a Fibonacci series in Java?

The Fibonacci series in Java is a number sequence where each number is the sum of the two numbers before it.

Q2. How is Fibonacci used in real life?

The Fibonacci numbers are used in many fields, like computing, the shape of shells, engineering, architecture, and even in financial markets.

Q3. Why is Fibonacci so important?

Fibonacci is important because it helps us to solve math problems efficiently, and is used in computer algorithms, science, and art.

Q4. What is the fastest way to generate Fibonacci numbers in Java?

Using dynamic programming or memoization offers fast and efficient performance with O(n) time. For very large n, matrix exponentiation provides O(log n) speed.

Q5. How to handle large Fibonacci numbers in Java?

Use the BigInteger class to calculate and store Fibonacci numbers beyond the range of int or long.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner