The Class Random

In this lesson, we’ll look at how Java provides values chosen at random.

Pseudorandom numbers

Applications such as games, lotteries, and simulations depend upon numbers that are chosen at random. Since computers are programmed, we cannot expect them to produce truly random numbers. Instead, we can create a sequence of numbers that does not repeat itself for a very long time. The numbers within any portion of this long sequence will appear to be random. Such numbers are called pseudorandom numbers, but we simply will call them random numbers. We use a random number generator to produce these numbers.

Seed

To begin a sequence of random numbers, we take a number called the seed that is used to generate the first random number. A seed can be any number. For example, the seed could be the time of day or a number that the user provides.

📝 Note

When we use a random number generator with a given seed to produce a sequence of n random numbers, and then we use the same generator with the same seed the next day to produce another sequence of n random numbers, the two sequences will be identical.

The class Random and its methods

The package java.util within the Java Class Library contains the class Random that we can use to produce random numbers. An object of this class is a random number generator. We create such an object by writing a statement like

Random generator = new Random();

The seed of this random number generator is the time of day at which the statement executes, given in milliseconds.

Once we have created the generator object, we can use it any number of times to produce as many random numbers as we want. We can get random integers or random real numbers, as follows:

  • generator.nextInt() returns a random integer of type int
  • generator.nextInt(n) returns a random integer of type int that is greater than or equal to zero and less than n for a positive integer n
  • generator.nextDouble() returns a random number of type double that is greater than or equal to 0 and less than 1

Get hands-on with 1200+ tech skills courses.