Implementazione iterativa dell’algoritmo di Fibonacci in Java.
Vengono stampati i primi n numeri, con n passato da console o generato casualmente, della successione:

import java.util.Random;

public class fibo
{
	public static void main(String[] args)
	{
		int n;
		try {
			n = Integer.parseInt(args[0]);
		}
		catch(ArrayIndexOutOfBoundsException e)
		{
			Random generator = new Random();
			n = generator.nextInt(20) + 1;
		}

		int current = 0;
		int next = 1;

		for(int i = 0; i < n; i++)
		{
			System.out.println(current);
			int temp = current;
			current = next;
			next += temp;
		}
	}
}