- Java Tutorial
- Java Introduction
- Java Features
- Java Simple Program
- JVM, JDK and JRE
- Java Syntax
- Java Comments
- Java Keywords
- Java Variables
- Java Literals
- Java Separators
- Java Datatypes
- Java Operators
- Java Statements
- Java Strings
- Java Arrays
- Control Statement
- Java If
- Java If-else
- Java If-else-if
- Java Nested If
- Java Switch
- Iteration Statement
- Java For Loop
- Java For Each Loop
- Java While Loop
- Java Do While Loop
- Java Nested Loop
- Java Break/Continue
- Java Methods
- Java Methods
- Java Method Parameters
- Java Method Overloading
- Java Recursion
- Java OOPS
- Java OOPs
- Java Classes/Objects
- Java Inheritance
- Java Polymorphism
- Java Encapsulation
- Java Abstraction
- Java Modifiers
- Java Constructors
- Java Interface
- Java static keyword
- Java this keyword
- Java File Handling
- Java File
- Java Create File
- Java Read/Write File
- Java Delete File
- Java Program To
- Add Two Numbers
- Even or Odd Numbers
- Reverse a String
- Swap Two Numbers
- Prime Number
- Fibonacci Sequence
- Palindrome Strings
- Java Reference
- Java String Methods
- Java Math Methods
Java Program To Print Fibonacci Sequence
The Fibonacci sequence is one of the most famous mathematical patterns in computer science. It begins with 0 and 1, and every subsequent number is the sum of the two preceding ones. This sequence appears everywhere from the branching of trees to the arrangement of a pinecone, and it is a frequent topic in coding interviews to test a developer's understanding of loops and logic.
In Java, we can generate this sequence efficiently using a simple for loop. Below is a clean, readable implementation of the Fibonacci sequence:
public class Fibonacci {
public static void main(String[] args) {
// Define how many numbers in the sequence we want to print
int terms = 10;
System.out.println("Printing the first " + terms + " terms of the Fibonacci sequence:");
printFibonacci(terms);
}
/**
* Prints the Fibonacci sequence using an iterative approach.
* @param n The number of terms to generate.
*/
static void printFibonacci(int n) {
// The sequence always starts with 0 and 1
long n1 = 0, n2 = 1;
for (int i = 1; i <= n; i++) {
System.out.print(n1 + (i == n ? "" : ", "));
// Calculate the next term
long nextTerm = n1 + n2;
// Shift values: n1 becomes n2, and n2 becomes the new calculated term
n1 = n2;
n2 = nextTerm;
}
System.out.println(); // New line for clean output
}
}
How the Logic Works
The program follows a straightforward iterative logic often called the "sliding window" approach. Here is the step-by-step breakdown:
- Initialization: we start with two variables,
n1(set to 0) andn2(set to 1). - The Loop: We run a loop from 1 up to the number of
nterms requested. - Printing: In each iteration, we print the current value of
n1. - The Calculation: We calculate the
nextTermby addingn1andn2together. - The Swap: To prepare for the next iteration, we move the value of
n2inton1, and the value ofnextTerminton2. This effectively "slides" our window forward one step in the sequence.
Real-World Applications
While calculating Fibonacci numbers might seem like a purely academic exercise, the logic behind it is used in several real-world development scenarios:
- Agile Estimation: Many development teams use the Fibonacci sequence (or a modified version) for "Story Pointing" to estimate the complexity of tasks.
- Financial Modeling: Fibonacci retracement levels are used in technical analysis for stock market and forex trading to identify potential support and resistance levels.
- Data Structures: The Fibonacci Heap is a specific type of data structure used in priority queue operations and algorithms like Dijkstra's shortest path.
int types have a maximum value of 2,147,483,647. Fibonacci numbers grow exponentially and will exceed this limit (integer overflow) by the 47th term. If you need to calculate more terms, use long or BigInteger.
nextTerm before updating the variables, which can lead to skipping the first "0" in the sequence or causing an "off-by-one" error.
n = 0 or a negative number, the loop should handle it gracefully or throw an IllegalArgumentException to ensure the program doesn't exhibit unexpected behavior.
This iterative approach is the standard way to solve this problem because it balances readability with high performance. By understanding how the variables shift in each step, you can apply similar logic to other sequence-based algorithms in Java.