Fibonacci Series Example in Java
On this page (10sections)
Introduction
Fibonacci Series is a classic Java console program that demonstrates the concept with complete source code and sample output. Conversion programs transform values between formats, units or representations.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Definition
The first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence, and each subsequent number is the sum of the previous two.
Formula
F_n = F_{n-1} + F_{n-2}
Fibonacci Series Example Program
import java.util.Scanner;
public class FibonacciSeries{
public static void main(String args[]) {
System.out.print("Enter the number : ");
Scanner in=new Scanner(System.in);
int num=in.nextInt();
System.out.println("\n\nFibonacci series upto " + num+" numbers : ");
for(int i=1; i<=num; i++){
System.out.print(fibonacciMethod(i) +" ");
}
}
public static int fibonacciMethod(int num){
if(num== 1 || num== 2){
return 1;
}
return fibonacciMethod(num-1) + fibonacciMethod(num-2);
}
public static int fibonacciLoop(int num){
if(num == 1 || num == 2){
return 1;
}
int num1=1, num2=1, fibonacci=1;
for(int i= 3; i<= num; i++){
fibonacci = num1 + num2;
num1 = num2;
num2 = fibonacci;
}
return fibonacci;
}
}
Sample Output
Enter the number : 7
Fibonacci series upto 7 numbers :
1 1 2 3 5 8 13
When to use
Use unit conversion programs when reading sensor data, building calculators, or localizing measurements for users.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
import java.util.Scanner;imports a class used later in the program. -
A
println/printcall writes text to the console — part of the sample output below. -
A
Scannerreads typed input from the keyboard (System.in). -
int num=in.nextInt();updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below. -
A loop repeats the block until its condition becomes false.
-
A
println/printcall writes text to the console — part of the sample output below.
Best Practices
- Use
double(orBigDecimalfor money) to avoid integer division rounding errors. - Apply multiplication before addition — match the formula order exactly.
- Validate input with
hasNextDouble()before reading, as shown in the Scanner examples.
Common Mistakes
- Using integer division (
9/5as1) instead of floating-point (9.0/5.0). - Applying the wrong formula order —
(C + 32) * 9/5is not the same asC * 9/5 + 32. - Forgetting to close the
Scannerwhen finished (callin.close()in longer programs).