Home » Core Java » Fibonacci Series in Java Example

About Aldo Ziflaj

Aldo Ziflaj
Aldo is a student of Computer Engineering and a programming addict. He spares his free time coding, whether mobile, web, or desktop programming. He is also one of the co-founders of Things Lab.

Fibonacci Series in Java Example

In mathematics, the Fibonacci series is a series of numbers, starting from 0 and 1, where every n-th number is the sum of (n-1)-th and (n-2)-th. It is named after Leonardo Fibonacci, an Italian mathematician who is considered as the most talented mathematician of the Middle Ages. He wrote about the series in his book Liber Abaci (Book of Calculation).

The Fibonacci numbers are used in the computational run-time analysis of Euclid’s algorithm to determine the greatest common divisor of two integers, in some pseudo-random number generator algorithms, in the IFF 8SVX audio file format lossy compression, etc.

The Fibonacci series in Java can be calculated in both recursive and non-recursive way. Of course, the recursive way is the worst since it can cause a stack overflow when the function is recursively called for large Fibonacci numbers.

Fibonacci Series without recursion

To see how to calculate the Fibonacci series using iteration, create a class called IterativeFibonacci with the following code:

IterativeFibonacci.java

package com.javacodegeeks.examples;

import java.util.Scanner;

public class IterativeFibonacci {

	public static void main(String[] args) {
		long primo = 0, secondo = 1;
		long terzo;
		Scanner stdIn = new Scanner(System.in);
		
		System.out.print("How many numbers do you want to print? ");
		int iter = stdIn.nextInt();
		for (int i=0;i<iter;i++) {
			System.out.print(primo + " ");
			terzo = primo + secondo;
			primo = secondo;
			secondo = terzo;
		}
		
		stdIn.close();

	}

}

In this example, I started the series from 0 and 1. Firstly, I get the amount of Fibonacci numbers the program has to print, then I make the calculations for the numbers.

This program makes the calculations based on three numbers. Initially, the program shows the first number, after that it calculates the third, then it moves to another number triplet; by making the second number its first and the third number its second. In the end, it goes to the initial point of printing the first number of the triplet, and so on.

The output of this program is this:

How many numbers do you want to print? 7
0 1 1 2 3 5 8

Fibonacci numbers with recursion

There is also another way of generating Fibonacci series, even though it may cause some problems sometimes. By using the recurrence relation Fn = Fn-1 + Fn-2 we can come up with a program to calculate the values of Fibonacci series using a recursive method.

To see this, create a class called RecursiveFibonacci with the following source code:

RecursiveFibonacci.java

package com.javacodegeeks.examples;

import java.util.Scanner;

public class RecursiveFibonacci {

	public static long fibonacci(long n) {
		if (n<0) throw new IllegalArgumentException("Can't accept negative arguments");
		return (n < 2) ? n : fibonacci(n-1) + fibonacci(n-2);
	}
	
	public static void main(String[] args) {
		Scanner stdIn = new Scanner(System.in);
		
		System.out.print("How many numbers do you want to print? ");
		int iter = stdIn.nextInt();
		for (int i=0;i<iter;i++) {
			System.out.print(fibonacci(i) + " ");
		}
		
		stdIn.close();

		
	}

}

The static fibonacci(long n) method is the one which calculates the n-th item. If n is smaller than 2 (i.e. 0 or 1), it returns that value. If n is greater than 2, it calculates the Fibonacci value based on the recurrence relation. Of course, since we can’t calculate Fibonacci values for negative numbers, the method would throw an IllegalArgumentException.

The output would be the same as in the first example:

How many numbers do you want to print? 7
0 1 1 2 3 5 8

 

Download Code

Download
You can download the full source code of this example here : FibonacciSeries

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments