Fundamentals 12 min read

Java Random Class: Constructors, Methods, and Implementation Details

This article provides a comprehensive overview of Java's Random class, describing its constructor, implemented interfaces, direct subclasses, and detailed explanations of all public methods—including setSeed, next, nextBytes, nextInt, nextLong, nextBoolean, nextFloat, nextDouble, and nextGaussian—along with the underlying linear‑congruential algorithm and code examples.

IT Xianyu
IT Xianyu
IT Xianyu
Java Random Class: Constructors, Methods, and Implementation Details

The Java Random class is a pseudo‑random number generator that can be instantiated with a specific seed to produce a deterministic sequence of values.

Implemented interfaces: Serializable

Direct known subclass: SecureRandom

Constructor:

public Random(long seed)

Creates a new generator using the given seed as the initial internal state.

Calling new Random(seed) is equivalent to:

Random rnd = new Random();
 rnd.setSeed(seed);

Method: setSeed

public void setSeed(long seed)

Resets the generator's seed to the value derived from (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1) and clears the haveNextNextGaussian flag used by nextGaussian() . The implementation uses only the low 48 bits of the supplied seed.

Method: next (protected)

protected int next(int bits)

Generates the next pseudo‑random number; subclasses should override this method. It updates the seed with the linear‑congruential formula (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1) and returns (int)(seed >>> (48 - bits)) . This algorithm was described by D. H. Lehmer and documented by Donald E. Knuth.

Method: nextBytes

public void nextBytes(byte[] bytes) {
    for (int i = 0; i < bytes.length; )
        for (int rnd = nextInt(), n = Math.min(bytes.length - i, 4);
             n-- > 0; rnd >>= 8)
            bytes[i++] = (byte)rnd;
}

Fills the supplied byte array with random bytes; throws NullPointerException if the array is null .

Method: nextInt()

public int nextInt() {
    return next(32);
}

Returns a uniformly distributed int value from the generator's sequence.

Method: nextInt(int n)

public int nextInt(int n) {
    if (n <= 0) throw new IllegalArgumentException("n must be positive");
    if ((n & -n) == n) // n is a power of 2
        return (int)((n * (long)next(31)) >> 31);
    int bits, val;
    do {
        bits = next(31);
        val = bits % n;
    } while (bits - val + (n - 1) < 0);
    return val;
}

Returns a uniformly distributed int in the range 0 (inclusive) to n (exclusive). The implementation avoids bias by rejecting values that would cause uneven distribution.

Method: nextLong()

public long nextLong() {
    return ((long)next(32) << 32) + next(32);
}

Returns a uniformly distributed long value; because the generator uses only a 48‑bit seed, not all long values are possible.

Method: nextBoolean()

public boolean nextBoolean() {
    return next(1) != 0;
}

Returns true or false with (approximately) equal probability.

Method: nextFloat()

public float nextFloat() {
    return next(24) / ((float)(1 << 24));
}

Returns a uniformly distributed float in the range 0.0f (inclusive) to 1.0f (inclusive). Early Java versions used next(30) , which introduced slight bias.

Method: nextDouble()

public double nextDouble() {
    return (((long)next(26) << 27) + next(27)) / (double)(1L << 53);
}

Returns a uniformly distributed double in the range 0.0 (inclusive) to 1.0 (exclusive). Earlier implementations used a different scaling factor that caused larger bias.

Method: nextGaussian()

private double nextNextGaussian;
private boolean haveNextNextGaussian = false;

public double nextGaussian() {
    if (haveNextNextGaussian) {
        haveNextNextGaussian = false;
        return nextNextGaussian;
    } else {
        double v1, v2, s;
        do {
            v1 = 2 * nextDouble() - 1; // between -1.0 and 1.0
            v2 = 2 * nextDouble() - 1;
            s = v1 * v1 + v2 * v2;
        } while (s >= 1 || s == 0);
        double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s) / s);
        nextNextGaussian = v2 * multiplier;
        haveNextNextGaussian = true;
        return v1 * multiplier;
    }
}

Generates a normally distributed (Gaussian) double with mean 0.0 and standard deviation 1.0 using the polar (Box‑Muller) method.

JavaProgrammingAlgorithmsRandomPseudo‑randomCore Library
IT Xianyu
Written by

IT Xianyu

We share common IT technologies (Java, Web, SQL, etc.) and practical applications of emerging software development techniques. New articles are posted daily. Follow IT Xianyu to stay ahead in tech. The IT Xianyu series is being regularly updated.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.