Java Basic Examples

Calculate Fibonacci series in Java example

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

What is 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 Fibonacci series in Java?

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

Calculate Fibonacci series using for loop

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

Output

Calculate Fibonacci series using recursion

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

Output

How to calculate Fibonacci series of large numbers?

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

Result is negative. This because int in Java is a 32 bit signed integer. Once we overflow that limit, it becomes a negative number. We will have to use long data type which is 64 bit. If even larger sum is required, we need to use BigInteger instead.

In order to calculate Fibonacci series of a large number we need to use BigInteger as given below.

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

 

Join 1000+ fellow learners! Enter your email address below: