# Fibonacci Series in Java

This is one of the articles from our Java Tutorial for Beginners.

**Your Task:**

Display the first 11 numbers of the Fibonacci sequence in the console.

A friendly reminder:

- The first and second numbers in the Fibonacci sequence are 1.
- And every following number is the sum of the two previous numbers.

This means that the numbers of the Fibonacci sequence are: 1 1 2 3 5 8 13 21 34 55 89 etc.

**Solution:**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class Test { public static void main(String[] args){ int n0 = 1; int n1 = 1; int n2; System.out.print(n0+" "+n1+" "); for(int i = 3; i <= 11; i++){ n2=n0+n1; System.out.print(n2+" "); n0=n1; n1=n2; } System.out.println(); } } |

**If you run this code on your computer, you will see the following in your console:**

1 1 2 3 5 8 13 21 34 55 89

**Commentary:**

We created 3 variables:

- We assigned the value "1" to the first 2 variables, because the first number (n0) and the second number (n1) of the Fibonacci sequence are both 1.
- We created a third variable and we called it n2.

1 2 3 |
int n0 = 1; int n1 = 1; int n2; |

And then we display the first two numbers of the Fibonacci sequence with the help of System.out.print(). To display these 2 numbers in a row, we used System.out.print() and not System.out.println().

1 |
System.out.print(n0+" "+n1+" "); |

To get the sum of the two previous numbers in the Fibonacci sequence, we use the "for" loop. And since we only need to display the first 11 numbers of the Fibonacci sequence, we write i<=11 as the condition of the "for" loop.

1 2 3 4 5 6 |
for(int i = 3; i <= 11; i++){ n2=n0+n1; System.out.print(n2+" "); n0=n1; n1=n2; } |

And then we write the following to display the numbers in the console:

1 |
System.out.println(); |

**You can find more articles in our ****Java Tutorial for Beginners. **