Using java.util.Random

In our introduction to random numbers in Java, we saw a brief example of generating random integers with the java.util.Random class. On this page, we'll look in a little more detail at how this class works. This will give us some guidance on how to use it most effectively, and when not to use it.

Tips for using java.lang.Random

First, some practical advice. If you don't want to get too theoretical, and you just want a casual random number generator, e.g. for a dice roll or the starting position of a baddy in your next blockbuster game, then java.lang.Random is still OK for that kind of use if you at least make the most of the class:

Next: how does java.lang.Random work, and how good is it?

If you want to understand the above issues in more detail, then the next section deals with the "Java Random algorithm", looking at how java.lang.Random works and some of its limitations.

You should also look at the section on alternatives to java.util.Random, which looks at various random number generators that you could use as a higher-quality replacement. In particular, you should look at:


1. Just to be clear: the simple test of >= effectively first tests if the number is positive or negative. That part will be reasonably random). Then in the case of the number being positive, the expression tests if bit 2 is set. This latter stage will introduce a high element of non-randomness.