The recursive solution follows the definition directly: fib(0) = 0, fib(1) = 1, and fib(n) = fib(n - 1) + fib(n - 2). Printing fib(0) to fib(n - 1) gives the first n numbers of the series.
import java.util.HashMap;
import java.util.Map;
public class FibonacciRecursion {
static int fib(int n) {
if (n <= 1) {
return n;
}
return fib(n - 1) + fib(n - 2);
}
private static final Map<Integer, Long> memo = new HashMap<>();
static long fibMemo(int n) {
if (n <= 1) {
return n;
}
Long cached = memo.get(n);
if (cached != null) {
return cached;
}
long value = fibMemo(n - 1) + fibMemo(n - 2);
memo.put(n, value);
return value;
}
public static void main(String[] args) {
int count = 10;
StringBuilder series = new StringBuilder();
for (int i = 0; i < count; i++) {
series.append(fib(i)).append(i < count - 1 ? " " : "");
}
System.out.println("First " + count + " numbers: " + series);
System.out.println("fib(50) with memoization: " + fibMemo(50));
}
}First 10 numbers: 0 1 1 2 3 5 8 13 21 34
fib(50) with memoization: 12586269025
Do not use computeIfAbsent() for the memo map in a recursive method: the nested calls modify the same HashMap during computeIfAbsent and can throw ConcurrentModificationException.
Write the plain recursive version, then say its O(2ⁿ) cost out loud and offer memoization or the loop; that is exactly the follow-up interviewers ask.
A concise interview answer is
I define fib(n) as n for n <= 1 and fib(n - 1) + fib(n - 2) otherwise, and print fib(0) to fib(n - 1). Plain recursion is O(2ⁿ) because it repeats work, so I add memoization to bring it down to O(n), or use a simple loop with two variables in real code.
Last updated: 11 November 2026
Previous question: Write a Java program to check whether a string or number is a palindrome.
Next question: Write a Java program to iterate an ArrayList using a for loop, a while loop and an enhanced for loop.