Fibonacci Series in Java
The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. In this post, we'll see how to generate the Fibonacci series using Java.
What is Fibonacci Series?
It starts with 0, 1
, and the next numbers in the sequence are formed by adding the previous two numbers:
0, 1, 1, 2, 3, 5, 8, 13, 21...
Java Program to Print Fibonacci Series
public class FibonacciExample { public static void main(String[] args) { int n = 10; 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; } } }
Output
Fibonacci Series up to 10 terms: 0 1 1 2 3 5 8 13 21 34
Explanation
- We start with two variables
a
andb
holding 0 and 1. - Each new term is calculated as
next = a + b
. - We update
a
andb
in each iteration to continue the series.
Conclusion
This is one of the most common Java programs asked in interviews. It’s simple and helps in understanding loops and variable manipulation.