Java Program To Print Fibonacci Sequence

Here's a Java program to print the Fibonacci sequence up to a specified number of terms:

public class Fibonacci {
    public static void main(String[] args) {
        int n = 10; // Number of terms
        printFibonacci(n);
    }

    static void printFibonacci(int n) {
        int n1 = 0, n2 = 1, n3;
        System.out.println("Fibonacci Sequence:");
        System.out.print(n1 + " " + n2); // Print first two terms

        for (int i = 2; i < n; i++) {
            n3 = n1 + n2;
            System.out.print(" " + n3);
            n1 = n2;
            n2 = n3;
        }
    }
}

This program calculates and prints the Fibonacci sequence up to the specified number of terms (n). It initializes the first two terms as 0 and 1, and then iteratively calculates the next terms by adding the previous two terms (n1 and n2). Finally, it prints each term in the sequence.