Running on Java 17+35-2724 (Preview)
Home of The JavaSpecialists' Newsletter

2.18 Fixing Random to be more random

Juppies 2 by Dr Heinz M. Kabutz

The bug in our shuffle() method was that we wrote

  Random random = new Random(0);

Instead of

  Random random = new Random();

One little number 0 and our game was not properly random anymore. The Random class generates a pseudo-random number sequence. Every time we call nextInt(), it gives us the next number in its sequence. It is surprisingly difficult to get true random numbers from computers. Having a pseudo-random (not true random) number sequence is an approximation that will work well enough in most cases, and is quite fast. The pseudo-random number sequence has to start at some position. By default, it will at some position determined partly by the System.nanoTime(). Every time we start the program, the System.nanoTime() will be a bit different, thus giving us a different start into the sequence.

Comments

When you load these comments, you'll be connected to Disqus. Privacy Statement.

Table of Contents

We hope you enjoyed this tutorial. If you did, you will also enjoy our courses. We suggest you start with Extreme Java - Advanced Java, followed by Extreme Java - Concurrency Performance for Java 8.



About the Author

Heinz Kabutz Java Conference Speaker

Java Champion, author of the Javaspecialists Newsletter, conference speaking regular... About Heinz

Superpack 21

Superpack 21 Our entire Java Specialists Training in one huge bundle more...

Free Java Course

Free Juppies 2 Course
Juppies 2 - a course for complete beginners more...

Free Java Book

Dynamic Proxies in Java Book
Java Training

We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations.

Java Consulting

We can help make your Java application run faster and trouble-shoot concurrency and performance bugs...

Java Emergency?

If your system is down, we will review it for 15 minutes and give you our findings for just 1 € without any obligation.