Random class is present in the
java.util package. It is used to generate random values or streams of random values of specific data types.
Random class can be accessed by importing it as follows:
When an instance of the
Random class is created, either a
seed value is passed to the constructor or no values are passed at all.
seed is a value that gets manipulated (using a linear congruential formula) to produce a stream of pseudorandom values. The
Random class uses a 48-bit
In this code, objects
rand2 of the
Random type are created using the
new keyword. While no parameters are passed during the creation of
seed value is used during the creation of
The value of the seed can be set or modified at any point during the execution of the program using the
Note: If two objects of type
Random are created with the same seed, they will generate the same sequence of numbers, provided they are subject to the same sequence of method calls.
Generating Individual Values
The following methods can be used to generate the next pseudorandom number from the generator’s sequence.
.nextFloat()methods return values in range [0,1). This means that the range is inclusive of zero (indicated by the square bracket) and exclusive of 1 (indicated by the parenthesis).
.nextLong()methods have no such limits.
Note: In the absence of a
seed, these methods return different values every time they are called or even for separate instances:
The output will look like this:
.nextInt() method can also be used with an upper bound so that the generated value is between 0 and that upper bound.
The output will be:
A byte array can also be filled with random elements using the
The output looks like this:
LongStream objects can be produced using the
.longs() methods, respectively.
The following example illustrates the generation of a
DoubleStream object and can be extrapolated for the other two object types as well.
To use an object of this type, the following import statement must be used:
An unlimited stream of pseudorandom
double values, each in the range [0,1), can be generated using the following code snippet. A
DoubleStream is a stream over objects of
An effectively unlimited stream of pseudorandom
double values, each in the range specified, can be generated using the following code snippet. The parameters are the lower bound and the upper bound, respectively:
Note: In the above method, the lower bound is inclusive but the upper bound is exclusive.
A stream of specified size of values in range [0,1) can be generated using the following code snippet. The parameter represents the size of the stream:
A stream of specified size with values in a specified range can be generated using the following code snippet. The parameters are the size of stream, the lower bound and the upper bound, respectively: