Fibonacci in Java

So we’ve seen lots of examples of our Fibonacci program in scripting languages, but other than C, I haven’t touched on many compiled languages. So here is a version in Java, probably one of the most common and popular languages in use today. Considered by advocates to be the among the best enterprise application development languages, we’ll see here how to write our simple program.

9 Responses to “Fibonacci in Java”

  1. Fibonacci in Ruby Says:

    […] « Fibonacci in Python Fibonacci in Java […]

  2. Pieter Says:

    you can do this a lot simpler.
    Using the Scanner to read the next int would get rid of that try catch and makes stuff a lot easier.

    here’s how i would do it…

    import java.util.Scanner;

    public class Fibonacci {

    public static void main(String[] args) {
    System.out.println(“How many numbers of the sequence would you like?”);

    // Create a SCanner that reads input from console
    Scanner scanner = new Scanner(System.in);

    // Get first int from scanner
    int n = scanner.nextInt();

    // Start Fibonacci algorithm
    fibonacci(n);
    }

    public static void fibonacci(int n) {
    int a = 0, b = 1;

    for (int i = 0; i

  3. Jeff F. Says:

    Speaking of Fibonacci… check out how the band Tool uses Fibonacci in their song Lateralus:

    http://youtube.com/watch?v=wS7CZIJVxFY

    …. Pretty cool stuff ….

  4. Philips Tel Says:

    Thank a lot for the script.

  5. Rajesh Says:

    Here is a program that does the same by using recursion. You should be familiar with such problems as well. Link

  6. Atul Kumar Singh Says:

    Actually,I believe the Fibonacci numbers can not be correctly generated using java’s primitive data types(byte, short int or ,long)

    All these datatypes are 8-64 bit signed two’s complement integer. What that means is that at some point in the computation you will end up with a -ve number if you are working with an infinite set.

    The posted code will break the fibonacci series when it generates the expected 48th number[2,971,215,073] it will output -1323752223 instead.

    atlisingh@gmail.com

  7. beth Says:

    hey Pieter,
    i tried to run your code but it was only printing out the :System.out.println(“How many numbers of the sequence would you like?”); it was not showing the fibonacci series.
    thanxs please get back to me if you can.

  8. Fibinachi java | Yodetus Says:

    […] Fibonacci in JavaJan 6, 2008 … Fibonacci in Java. So we’ve seen lots of examples of our Fibonacci program in scripting languages, but other than C, I haven’t touched on … […]

  9. Steven Says:

    Beth, you need to type the amount of numbers you want generated and then hit return… if you want the first 10 in the series type 10 and hit return.