Java Reference
In-Depth Information
In addition to the methods shown in Figure 15-3 , nextBoolean() returns either true or false with equal
probability, and nextBytes() that fills the byte[] array you supply as the argument with a sequence of
bytes with random values; NullPointerException is thrown if the argument is null .
There are two constructors for a Random object. The default constructor creates an object that uses the
current time from your computer clock as the seed value for generating pseudo-random numbers. The other
constructor accepts an argument of type long that is used as the seed.
Random lottery = new Random(); // Sequence not repeatable
Random repeatable = new Random(997L); // Repeatable sequence
If you use the default constructor, the sequence of numbers that is generated is different each time a pro-
gram is run, although beware of creating two generators in the same program with the default constructor.
The time resolution can be down to nanoseconds but it is only guaranteed to be no greater than 1 milli-
second. If you create two objects in successive statements they may generate the same sequence because the
times used for the starting seed values were identical.
Random objects that you create using the same seed always produce the same sequence, which can be
very important when you are testing a program. Testing a program where the output is not repeatable can be
a challenge! A major feature of random number generators you create using a given seed in Java is that not
only do they always produce the same sequence of pseudo-random numbers, but they also do so on totally
different computers.
Random Operations
The public methods provided by a Random object are the following:
Search WWH ::




Custom Search