Posts

Java Fibonacci examples

Few Java examples to find the Fibonacci numbers.

1. Java 8 stream

1.1 In Java 8, we can use Stream.iterate to generate Fibonacci numbers like this :

 Stream.iterate(new int[]{0, 1}, t -> new int[]{t[1], t[0] + t[1]})
 .limit(10)
 .forEach(x -> System.out.println("{" + x[0] + "," + x[1] + "}"));

Output

{0,1}
{1,1}
{1,2}
{2,3}
{3,5}
{5,8}
{8,13}
{13,21}
{21,34}
{34,55}

P.S Review the above output, the first value is what we wanted.

1.2 Final version.

 Stream.iterate(new int[]{0, 1}, t -> new int[]{t[1], t[0] + t[1]})
 .limit(10)
 .map(t -> t[0])
 .forEach(x -> System.out.println(x));

Output

0
1
1
2
3
5
8
13
21
34

1.3 Sum all the Fibonacci numbers

 int sum = Stream.iterate(new int[]{0, 1}, t -> new int[]{t[1], t[0] + t[1]})
 .limit(10)
 .map(t -> t[0])
 .mapToInt(Integer::intValue)
 .sum();

    System.out.println("Total : " + sum);

Output

Total : 88

1.4 Join with commas.

String collect = Stream.iterate(new int[]{0, 1}, t -> new int[]{t[1], t[0] + t[1]})
                .limit(10)
                .map(t -> t[0])
                .map(String::valueOf) // convert to string
                .collect(Collectors.joining(", "));

        System.out.println("Result : " + collect);

Output

Result : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

1.5 A function to create a List of Fibonacci numbers.

package com.mkyong.concurrency;

import java.util.List;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;

public class Fibonacci {

    public static List<Integer> getFibonacci(int series) {
        return Stream.iterate(new int[]{0, 1}, t -> new int[]{t[1], t[0] + t[1]})
                .limit(series)
                .map(n -> n[0])
                .collect(toList());
    }

    public static void main(String[] args) {

        List<Integer> fibonacci = getFibonacci(10);
        fibonacci.forEach(x -> System.out.println(x));

    }

}

Output

0
1
1
2
3
5
8
13
21
34

1.6 The type int and long are not enough to store larger Fibonacci numbers. Below is the BigInteger example to find the first million Fibonacci numbers.

package com.mkyong.concurrency;

import java.math.BigInteger;
import java.util.stream.Stream;

public class Fibonacci {

    public static BigInteger getFibonacci(int series) {
        return Stream.iterate(new BigInteger[]{
                BigInteger.ZERO, BigInteger.ONE}, t -> new BigInteger[]{t[1], t[0].add(t[1])})
                .limit(series)
                .map(n -> n[1]) // find, we need n[1]
                .reduce((a, b) -> b).orElse(BigInteger.ZERO);

    }

    public static void main(String[] args) {
        System.out.println(Fibonacci.getFibonacci(1_000_000));
    }

}

Output

1953282128707757731632014947596256332443... // 208,988 digits!!!, too long to display here

2. Recursive Loop

2.1 Java recursive loop example to create a list of Fibonacci numbers. Good to demo only, this recursive loop is slow.Fibonacci.java

package com.mkyong.concurrency;

public class Fibonacci {

    public static int fib(int n) {
        if (n <= 1) return n;
        else return fib(n - 1) + fib(n - 2);
    }
    
    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            System.out.println(fib(i));
        }

    }


}

Output

0
1
1
2
3
5
8
13
21
34

2.2 How it works?

fib(n) = fib(n - 1) + fib(n - 2);

fib(5) = fib(4) + fib(3);
fib(4) = fib(3) + fib(2);
fib(3) = fib(2) + fib(1);
fib(2) = fib(1) + fib(0);
fib(1) = 1
fib(0) = 1

3. Normal Loop

3.1 Java normal loop to find the Fibonacci numbers, simple and easy.Fibonacci.java

package com.mkyong.concurrency;

import java.math.BigInteger;

public class Fibonacci {

    public static int fib(int n) {
        if (n <= 1) return n;

        int previous = 0, next = 1, sum;

        for (int i = 2; i <= n; i++) {
            sum = previous;
            previous = next;
            next = sum + previous;
        }

        return next;
    }

    public static BigInteger fib2(int n) {
        if (n <= 1) return BigInteger.valueOf(n);

        BigInteger previous = BigInteger.ZERO, next = BigInteger.ONE, sum;

        for (int i = 2; i <= n; i++) {
            sum = previous;
            previous = next;
            next = sum.add(previous);
        }

        return next;
    }

    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            System.out.println(fib(i));
        }

        System.out.println("---");

        for (int i = 0; i < 10; i++) {
            System.out.println(fib2(i));
        }

        System.out.println("---");

        System.out.println(fib(100)); //overflow
        System.out.println(fib2(100));
    }

}

Output

0
1
1
2
3
5
8
13
21
34
---
0
1
1
2
3
5
8
13
21
34
---
-980107325
354224848179261915075
Copy

Note
Please use BigInteger to store the Fibonacci numbers to avoid an overflow issue.

Java – what is -Xms and -Xmx parameter?

In Java, -Xms set initial Java heap size, while -Xmx set the maximum Java heap size.

1. Some java -Xms -Xmx examples :

# Start with 128MB of memory, and allow the Java process to use up to 1024MB of memory. 
java -Xms128m -Xmx1024m
# Start with 256MB of memory, and allow the Java process to use up to 4G (4096MB) of memory.
java -Xms256m -Xmx4g

2. The default initial and maximum Java heap size is allocated based on this ergonomics algorithm , also read this article – Find out your Java heap memory size

3. If the Java process has exceeded the -Xmx maximum Java heap size, the popular java.lang.OutOfMemoryError will be thrown.

4. For other options, run this java -X

> java -X

    -Xbatch           disable background compilation
    -Xbootclasspath/a:<directories and zip/jar files separated by ;>
                      append to end of bootstrap class path
    -Xcheck:jni       perform additional checks for JNI functions
    -Xcomp            forces compilation of methods on first invocation
    -Xdebug           provided for backward compatibility
    -Xdiag            show additional diagnostic messages
    -Xfuture          enable strictest checks, anticipating future default
    -Xint             interpreted mode execution only
    -Xinternalversion
                      displays more detailed JVM version information than the
                      -version option
    -Xloggc:<file>    log GC status to a file with time stamps
    -Xmixed           mixed mode execution (default)
    -Xmn<size>        sets the initial and maximum size (in bytes) of the heap
                      for the young generation (nursery)
    -Xms<size>        set initial Java heap size
    -Xmx<size>        set maximum Java heap size
    -Xnoclassgc       disable class garbage collection
    -Xrs              reduce use of OS signals by Java/VM (see documentation)
    -Xshare:auto      use shared class data if possible (default)
    -Xshare:off       do not attempt to use shared class data
    -Xshare:on        require using shared class data, otherwise fail.
    -XshowSettings    show all settings and continue
    -XshowSettings:all
                      show all settings and continue
    -XshowSettings:locale
                      show all locale related settings and continue
    -XshowSettings:properties
                      show all property settings and continue
    -XshowSettings:vm
                      show all vm related settings and continue
    -XshowSettings:system
                      (Linux Only) show host system or container
                      configuration and continue
    -Xss<size>        set java thread stack size
    -Xverify          sets the mode of the bytecode verifier

History of Java?

The history of Java is very interesting. Java was originally designed for interactive television, but it was too advanced technology for the digital cable television industry at the time. The history of java starts with Green Team. Java team members (also known as Green Team), initiated this project to develop a language for digital devices such as set-top boxes, televisions, etc. However, it was suited for internet programming. Later, Java technology was incorporated by Netscape.

The principles for creating Java programming were “Simple, Robust, Portable, Platform-independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted and Dynamic”.

James Gosling - founder of java

Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc. There are given the significant points that describe the history of Java.

Java History from Oak to Java

1) James GoslingMike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The small team of sun engineers called Green Team.

2) Originally designed for small, embedded systems in electronic appliances like set-top boxes.

3) Firstly, it was called “Greentalk” by James Gosling, and file extension was .gt.

4) After that, it was called Oak and was developed as a part of the Green project.

Why Java named “Oak”?

5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like U.S.A., France, Germany, Romania, etc.

6) In 1995, Oak was renamed as “Java” because it was already a trademark by Oak Technologies.

Why Java Programming named “Java”?

7) Why had they chosen java name for java language? The team gathered to choose a new name. The suggested words were “dynamic”, “revolutionary”, “Silk”, “jolt”, “DNA”, etc. They wanted something that reflected the essence of the technology: revolutionary, dynamic, lively, cool, unique, and easy to spell and fun to say.

According to James Gosling, “Java was one of the top choices along with Silk“. Since Java was so unique, most of the team members preferred Java than other names.

8) Java is an island of Indonesia where first coffee was produced (called java coffee).

9) Notice that Java is just a name, not an acronym.

10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation) and released in 1995.

11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.

12) JDK 1.0 released in(January 23, 1996).


Java Version History

Many java versions have been released till now. The current stable release of Java is Java SE 10.

  1. JDK Alpha and Beta (1995)
  2. JDK 1.0 (23rd Jan 1996)
  3. JDK 1.1 (19th Feb 1997)
  4. J2SE 1.2 (8th Dec 1998)
  5. J2SE 1.3 (8th May 2000)
  6. J2SE 1.4 (6th Feb 2002)
  7. J2SE 5.0 (30th Sep 2004)
  8. Java SE 6 (11th Dec 2006)
  9. Java SE 7 (28th July 2011)
  10. Java SE 8 (18th March 2014)
  11. Java SE 9 (21st Sep 2017)
  12. Java SE 10 (20th March 2018)

Java Tutorial – Java Complete Tutorial

Our core Java programming tutorial is designed for students and working professionals. Java is an object-oriented, class-based, concurrent, secured and general-purpose computer-programming language. It is a widely used robust technology.

What is Java

Java is a programming language and a platform.

Java is a high level, robust, object-oriented and secure programming language.

Platform: Any hardware or software environment in which a program runs, is known as a platform. Since Java has a runtime environment (JRE) and API, it is called a platform.


Java Example

Let’s have a quick look at Java programming example. A detailed description of hello Java example is available in next page.

  1. class Simple{  
  2.     public static void main(String args[]){  
  3.      System.out.println(“Hello Java”);  
  4.     }  
  5. }  

Application

According to Sun, 3 billion devices run Java. There are many devices where Java is currently used. Some of them are as follows:

  1. Desktop Applications such as acrobat reader, media player, antivirus, etc.
  2. Web Applications such as irctc.co.in, javatpoint.com, etc.
  3. Enterprise Applications such as banking applications.
  4. Mobile
  5. Embedded System
  6. Smart Card
  7. Robotics
  8. Games, etc.

Types of Java Applications

There are mainly 4 types of applications that can be created using Java programming:

1) Standalone Application

Standalone applications are also known as desktop applications or window-based applications. These are traditional software that we need to install on every machine. Examples of standalone application are Media player, antivirus, etc. AWT and Swing are used in Java for creating standalone applications.

2) Web Application

An application that runs on the server side and creates a dynamic page is called a web application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for creating web applications in Java.

3) Enterprise Application

An application that is distributed in nature, such as banking applications, etc. is called enterprise application. It has advantages of the high-level security, load balancing, and clustering. In Java, EJB is used for creating enterprise applications.

4) Mobile Application

An application which is created for mobile devices is called a mobile application. Currently, Android and Java ME are used for creating mobile applications.

Java Platforms / Editions

There are 4 platforms or editions of Java:

1) Java SE (Java Standard Edition)

It is a Java programming platform. It includes Java programming APIs such as java.lang, java.io, java.net, java.util, java.sql, java.math etc. It includes core topics like OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing, Reflection, Collection, etc.

2) Java EE (Java Enterprise Edition)

It is an enterprise platform which is mainly used to develop web and enterprise applications. It is built on the top of the Java SE platform. It includes topics like Servlet, JSP, Web Services, EJB, JPA, etc.

3) Java ME (Java Micro Edition)

It is a micro platform which is mainly used to develop mobile applications.

4) JavaFX

It is used to develop rich internet applications. It uses a light-weight user interface API.


Prerequisite

To learn Java, you must have the basic knowledge of C/C++ programming language.

Audience

Our Java programming tutorial is designed to help beginners and professionals.

Problem

We assure that you will not find any problem in this Java tutorial. However, if there is any mistake, please post the problem in the contact form.