The Random class of java.util package contains methods in handling Random numbers as the class name implies. An instance of this class is used to generate a stream of pseudorandom numbers. A 48-bit seed has been used on this class, and these seed is modified using a linear congruential formula.

A particular scenario wherein if two instances of Random class are created using the same value on it’s seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. This is a must have property of this class and in order to guarantee as such, particular algorithms are specified for Random class. Java implementations must use all the algorithms shown here for the class Random, for the sake of absolute portability of Java code. However, subclasses of class Random are permitted to use other algorithms, so long as they adhere to the general contracts for all the methods.

Random Class Syntax

public class Random
extends Object
implements Serializable

Random Class Compatibility Version

Random Class is available since Java 1.0

Basic Usage of Random

The Random class as part of the java.util package is one of the classes of the java api that is fundamentally a must to learn as it is one of the foundation classes of Java. Being available since Java 1.0, this class has widely usage in the language.

Below is how you instantiate a new Random object.

Random rand = new Random();

There are two overloaded constructor of Random class. The first one is the one we showed above and the other which accepts a seed method argument.

Random Method Usage Examples

Modifier and Type Method and Description
DoubleStream doubles()
Returns an effectively unlimited stream of pseudorandom double values, each between zero (inclusive) and one (exclusive).