Skip to content

Calculate Fibonacci series in Java example

Calculate Fibonacci series example shows how to calculate and print Fibonacci series in Java using for loop (non-recursive) or using recursion and calculating Fibonacci for large numbers.

What is the Fibonacci series?

From Wikipedia,

In mathematics, the Fibonacci numbers or Fibonacci sequence are the numbers in the following integer sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144…

The Fibonacci sequence is named after Italian mathematician Leonardo of Pisa, known as Fibonacci.

How to calculate the Fibonacci series in Java?

The Fibonacci series can be calculated in two ways, using for loop (non-recursive) or using a recursion.

Using for loop

The Fibonacci series can be calculated using for loop as given in the below example.

Output

Using recursion

The Fibonacci series can also be calculated using the recursive method as given below.

Output

How to calculate the series of large numbers?

Let’s try to calculate the Fibonacci series for 50 numbers using the above program.

Output

As you can see from the output, the result started to become negative for larger numbers. This is because the int in Java is a 32 bit signed integer. Once we overflow that limit, it becomes a negative number. We can use the long data type which is 64 bit in Java. If we want to calculate the series for even larger numbers, the BigInteger should be used instead of long as given below.

This example is a part of the Java Basic Examples.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.