Before we create fibonacci series program in Java, let's understand what does Fibonacci program would actual mean, the Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, and characterized by the fact that every number after the first two is the sum of the two preceding ones.

So for example, fibonacci series from 1 to 5 would have numbers

0 1 1 2 3 5 8

Basically we start sequence from 0 and 1 then we add both number to get third number = 1

Then again last two numbers are added, that is ,1 +1 now, = 2.

again we add last two numbers, that is, 1+2 now = 3

we will keep adding last two numbers until our required position number is not hit by loop.

Fibonacci Series in Java

public class Main
{
	 public void fibonacci(int num){
          int a=0, b=1;
          int c;
          System.out.print(a + " "+b );

          //loop through numbers, below 'num' 
          for(int i=2;i<num;i++){
              c = a+b;
              a = b;
              b = c;
              System.out.print(" "+c);            
          }
      }

     //recursive method to add last 2 numbers
      public int recFibonacci(int a, int b){
          int c =a+b;
          return c;        
      }
      public static void main(String[] args){
          Main  fib = new Main();
          fib.fibonacci(10);        
      }
}

Output:

0 1 1 2 3 5 8 13 21 34

In the above code, we are taking Fibonacci series until "10" is reached in loop.

fibonacci-series-in-java-min.png

You may also like to read:

Java Pattern Program Examples