Fibonacci Algorithm in Java
The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …
1) The Recursive Approach (Simplest code, poor performance)
This directly mimics the mathematical definition of Fibonacci (F(n) = F(n-1) + F(n-2)). However, it is highly inefficient for large numbers because it recalculates the same values over and over.
public class FibonacciRecursive {
public static int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
public static void main(String[] args) {
int n = 10;
System.out.print("Fibonacci Series up to " + n + " terms: ");
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
}- Time Complexity:O(2^n)
- Space Complexity: 0(n) (stack)
- Pros: Very simple and readable code.
- Cons: Terrible time complexity O(2^n). Trying to find
fibonacci(50)this way will cause your program to freeze.
2) Memoization / Dynamic Programming (Optimized Recursion)
If you must use recursion but want it to be fast, you use Memoization. This technique stores the results of expensive function calls in an array (a cache) so you don’t re-calculate them.
public class FibonacciMemoization {
private static int[] cache;
public static int fibonacci(int n) {
if (n <= 1) return n;
// If we already calculated it, just return it
if (cache[n] != 0) return cache[n];
// Otherwise, calculate and store it
cache[n] = fibonacci(n - 1) + fibonacci(n - 2);
return cache[n];
}
public static void main(String[] args) {
int n = 10;
cache = new int[n];
System.out.print("Fibonacci Series: ");
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
}- Time Complexity:O(n)
- Space Complexity: 0(n)
- Pros: Drops the time complexity down to a blazing-fast O(n).
- Cons: Uses extra memory O(n) space complexity to store the array.
3) The Iterative Approach (Best for general use)
This is the most efficient and practical way to print or find a Fibonacci number. It uses a simple loop and has a time complexity of O(n) and space complexity of O(1).
public class FibonacciIterative {
public static void printFibonacci(int n) {
int a = 0, b = 1;
System.out.print("Fibonacci Series up to " + n + " terms: ");
for (int i = 1; i <= n; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
}
public static void main(String[] args) {
printFibonacci(10); // Outputs first 10 numbers
}
}- Time Complexity: O(n)
- Space Complexity: 0(1)
- Pros: Highly efficient, no risk of StackOverflowError.
- Cons: Not as “elegant-looking” as recursion.
4) Java 8 Streams Approach (The Functional Way)
If you love modern, functional Java, you can generate the Fibonacci series using Stream.iterate.
import java.util.stream.Stream;
public class FibonacciStream {
public static void main(String[] args) {
int n = 10;
System.out.print("Fibonacci Series via Streams: ");
Stream.iterate(new int[]{0, 1}, f -> new int[]{f[1], f[0] + f[1]})
.limit(n)
.map(f -> f[0])
.forEach(num -> System.out.print(num + " "));
}
}- Time Complexity: O(n)
- Space Complexity: 0(1)
- Pros: Compact, declarative, and elegant.
- Cons: Marginally slower than the basic iterative loop due to object boxing, but perfectly fine for everyday use
Production Best Practices
If you plan to deploy Fibonacci code into a high-scale production environment, there are a few subtle but major traps that can crash your application or cause incorrect data.
Get Kandaanusha’s stories in your inbox
Join Medium for free to get updates from this writer.
Here are the primary production issues you need to watch out for, along with how to fix them:
1. Integer Overflow (The Silent Bug)
The Fibonacci sequence grows exponentially. A standard Java 32-bit int will overflow surprisingly fast, resulting in negative numbers or garbage data.
intoverflows at n = 47longoverflows at n = 93
The Fix:
If you need to calculate large Fibonacci numbers beyond the 92nd term, you must use BigInteger. While this prevents data corruption, it introduces a fresh infrastructure hazard: CPU Starvation.
BigInteger objects are immutable. Every addition requires allocating a new array of ints under the hood, scaling in time complexity based on the number of digits. If an API accepts an unvalidated request for $n = 1,000,000$, the CPU will instantly peg at 100% utilization computing the result. Saturated cores mean failed load-balancer health checks, dropped traffic, and cascading timeouts across your microservices.
import java.math.BigInteger;
public class ProductionFibonacci {
public static BigInteger getLargeFibonacci(int n) {
BigInteger a = BigInteger.ZERO;
BigInteger b = BigInteger.ONE;
for (int i = 1; i <= n; i++) {
BigInteger next = a.add(b);
a = b;
b = next;
}
return a;
}
}2. StackOverflowError in Recursion
If your code uses the naive recursive or even the memoized recursive approach, every function call adds a frame to the JVM call stack.
- If a user requests a high number (e.g., n = 10,000), the stack depth will exceed the JVM’s memory limits, abruptly crashing the thread with a
java.lang.StackOverflowError.
The Fix:
- Never use recursion for open-ended inputs in production. Convert the logic to an iterative loop.
3. Memory Leaks in Memoization (The OutOfMemoryError Trap)
If you chose the Memoization/Dynamic Programming approach using a static map or cache (like HashMap<Integer, Long>), that cache will live in memory forever.
- If your application handles thousands of unique, large requests, your JVM will eventually run out of heap memory and throw an
OutOfMemoryError(OOM).
The Fix:
- Use the Iterative approach instead, as it uses O(1) constant memory.
- If you absolutely need a cache, use a proper caching library like Guava or Caffeine with a Time-To-Live (TTL) or maximum size limit configured.
4. Multi-Threaded Concurrency Issues
If you are running this code inside a web server (like a Spring Boot application) and multiple user threads are updating or reading a shared cache (like the cache array or HashMap from the previous example) at the same time, it will cause race conditions or memory visibility issues.
The Fix:
- Keep variables local to the method so they are inherently thread-safe.
- If a global cache is required, use a thread-safe data structure like
ConcurrentHashMap.
Production Grade Code
To make this production-ready, we must combine strict input validation, constant space complexity O(1), arbitrary-precision math, and thread isolation.
Below is the definitive, production-grade implementation for calculating a Fibonacci sequence in Java:
package com.enterprise.math;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
/**
* Production-ready utility for generating Fibonacci sequences.
* Designed for thread-safety, memory efficiency, and input resilience.
*/
public final class ProductionFibonacci {
// Strictly enforce an upper boundary to prevent CPU Starvation DoS attacks
private static final int MAX_ALLOWED_TERM = 10_000;
private ProductionFibonacci() {
// Prevent instantiation of utility class
}
/**
* Generates a list of Fibonacci numbers up to the specified number of terms.
*
* @param terms The number of terms to generate.
* @return A list containing the Fibonacci sequence.
* @throws IllegalArgumentException if terms is out of safe production bounds.
*/
public static List<BigInteger> generateSequence(int terms) {
// 1. Guard Clauses & Input Validation
if (terms < 0) {
throw new IllegalArgumentException("Sequence terms cannot be negative.");
}
if (terms > MAX_ALLOWED_TERM) {
throw new IllegalArgumentException(
String.format("Input exceeds safe limits. Maximum allowed terms is %d to protect system stability.", MAX_ALLOWED_TERM)
);
}
List<BigInteger> sequence = new ArrayList<>(terms);
if (terms == 0) {
return sequence;
}
// 2. Localized, Thread-Safe Iteration
BigInteger first = BigInteger.ZERO;
sequence.add(first);
if (terms == 1) {
return sequence;
}
BigInteger second = BigInteger.ONE;
sequence.add(second);
// O(1) auxiliary space loop (excluding the output container)
for (int i = 2; i < terms; i++) {
BigInteger next = first.add(second); // Generates a new BigInteger safely
sequence.add(next);
// Shift pointers forward
first = second;
second = next;
}
return sequence;
}
}



