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. The series looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on. In this article, we will explore various methods to generate and print the Fibonacci series in Java.
Method 1. Using Iteration in Java
The iterative approach uses loops to calculate the Fibonacci numbers. This method is efficient and easy to understand.
import java.util.Scanner;
public class FibonacciIterative {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of terms: ");
int n = scanner.nextInt();
int firstTerm = 0, secondTerm = 1;
System.out.println("Fibonacci Series up to " + n + " terms:");
for (int i = 1; i <= n; i++) {
System.out.print(firstTerm + ", ");
int nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
scanner.close();
}
}
Explanation
- We take the number of terms as input from the user.
- We use a for loop to iterate through the number of terms and print each term.
- The next term is calculated by summing the previous two terms.
Output

Method 2. Using Recursion in Java
The recursive approach involves a function that calls itself to calculate Fibonacci numbers. This method is elegant but can be inefficient for large inputs due to repeated calculations.
Code Example
import java.util.Scanner;
public class FibonacciRecursive {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of terms: ");
int n = scanner.nextInt();
System.out.println("Fibonacci Series up to " + n + " terms:");
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + ", ");
}
scanner.close();
}
public static int fibonacci(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
Explanation
- The Fibonacci method calculates the nth Fibonacci number using recursion.
- The main method iterates through the number of terms and prints each Fibonacci number by calling fibonacci(i).
Output




Join the conversation! Your thoughts help the community grow.