THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1
Sets the seed of the random number generator to seed. This method can be
invoked at any time and resets the sequence to start with the given seed.

public booleannextBoolean()

Returns a pseudorandom uniformly distributed boolean value.

public intnextInt()

Returns a pseudorandom uniformly distributed int value between the two
values Integer.MIN_VALUE and Integer.MAX_VALUE, inclusive.

public intnextInt(int ceiling)

Like nextInt(), but returns a value that is at least zero and is less than the
value ceiling. Use this instead of using nextInt() and % to get a range.
If ceiling is negative, an IllegalArgumentException is thrown.

public longnextLong()

Returns a pseudorandom uniformly distributed long value between
Long.MIN_VALUE and Long.MAX_VALUE, inclusive.

public voidnextBytes(byte[] buf)

Fills the array buf with random bytes.

public floatnextFloat()

Returns a pseudorandom uniformly distributed float value between 0.0f
(inclusive) and 1.0f (exclusive).

public doublenextdouble()

Returns a pseudorandom uniformly distributed double value between 0.0
(inclusive) and 1.0 (exclusive).

public doublenextGaussian()

Returns a pseudorandom Gaussian-distributed double value with mean of
0.0 and standard deviation of 1.0.

All the nextType methods use the protected method next. The next method takes an int that represents
the number of random bits to produce (between 1 and 32) and returns an int with that many bits. These
random bits are then converted to the requested type. For example, nextInt simply returns next(32),
while nextBoolean returns TRue if next(1) is not zero, else it returns false.


You can safely use Random from multiple threads.


The Random class specifies the algorithms to be used to generate the pseudo-random numbers but permits
different algorithms to be used provided the general contract of each method is adhered to. The basic
algorithm (a linear congruential generator) is defined in the next method and is used for all other methods
except nextGaussian. You can create your own random number generator by overriding the next
method to provide a different generating algorithm.

Free download pdf