How to Create Randomness in Java - dummies

How to Create Randomness in Java

By Barry A. Burd

As part of your programming with Java, you may be looking to create randomness. Achieving real randomness is surprisingly difficult. Mathematician Persi Diaconis says that if you flip a coin several times, always starting with the head side up, you’re likely to toss heads more often than tails. If you toss several more times, always starting with the tail side up, you’ll likely toss tails more often than heads. In other words, coin tossing isn’t really fair.*

* Diaconis, Persi. “The Search for Randomness.” American Association for the Advancement of Science annual meeting. Seattle. 14 Feb. 2004.

Computers aren’t much better than coins and human thumbs. A computer mimics the generation of random sequences, but in the end the computer just does what it’s told and does all of this in a purely deterministic fashion. So, when the computer executes

import java.util.Random;

int randomNumber = new Random().nextInt(10) + 1;

the computer appears to give a randomly generated number — a whole number between 1 and 10. But it’s all a fake. The computer only follows instructions. It’s not really random, but without bending a computer over backward, it’s the best that anyone can do.

Once again, you will simply have to take this code on blind faith. Don’t worry about what new Random().nextInt means until you have more experience with Java. Just copy this code into your own programs and have fun with it. And if the numbers from 1 to 10 aren’t in your flight plans, don’t fret. To roll an imaginary die, write the statement

int rollEmBaby = new Random().nextInt(6) + 1;

With the execution of this statement, the variable rollEmBaby gets a value from 1 to 6.