Java Fibonacci
last modified July 6, 2020
Java Fibonacci tutorial shows how to calculate Fibonacci series in Java. We create several algorithms for calculating Fibonacci series.
Fibonacci series is a sequence of values such that each number is the sum of the two preceding ones, starting from 0 and 1. The beginning of the sequence is thus: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ...
In this tutorial we show several ways to generate a fibonacci series in Java.
Since fibonacci series is a sequence of infinite numbers, we use BigInteger
type for calculations.
Java fibonacci classic loop example
The first algorithm uses a for loop.
package com.zetcode; import java.math.BigInteger; public class FibonacciLoopEx { public static BigInteger fibonacci(int n) { if (n <= 1) return BigInteger.valueOf(n); BigInteger previous = BigInteger.ZERO, next = BigInteger.ONE, sum; for (int i = 2; i <= n; i++) { sum = previous; previous = next; next = sum.add(previous); } return next; } public static void main(String[] args) { for (int i = 0; i <= 99; i++) { BigInteger val = fibonacci(i); System.out.println(val); } } }
The example prints first one-hundred values of a Fibonacci series.
Java Fibonacci recursive example
In the second example, we calculate the Fibonacci series using
a recursive algorithm where the fibonacci()
method calls
itself to do the calculation.
package com.zetcode; import java.math.BigInteger; public class FibonacciRecursiveEx { public static BigInteger fibonacci(int n) { if (n == 0 || n == 1) { return BigInteger.ONE; } return fibonacci(n - 2).add(fibonacci(n - 1)); } public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.println(fibonacci(i)); } } }
The example calculates the first ten values of a fibonacci sequence.
Java fibonacci stream example
The third example uses Java 8 streams for the calculation.
package com.zetcode; import java.math.BigInteger; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class FibonacciStreamEx { public static List<BigInteger> fibonacci(int limit) { var vals = Stream.iterate(new BigInteger[] { BigInteger.ZERO, BigInteger.ONE }, t -> new BigInteger[] { t[1], t[0].add(t[1]) }) .limit(limit) .map(n -> n[1]) .collect(Collectors.toList()); return vals; } public static void main(String[] args) { System.out.println(fibonacci(100)); } }
This example calculates the values up to a certain limit.
In this tutorial, we have shown how to calculate Fibonacci series in Java in three different ways: classic loop, recursive algorithm and functional way.
List all Java tutorials.