Leepoint Java Reference Notes on the Java language and its standard library.

Random numbers

Pseudo-random: deterministic given the seed, which is a feature.

Random rnd = new Random();
int n = rnd.nextInt(100);        // 0 to 99
double d = rnd.nextDouble();     // 0.0 up to but excluding 1.0
boolean b = rnd.nextBoolean();

Math.random() returns a double in [0, 1) and is a thin wrapper over a shared Random. Fine for a one-off; a Random instance is clearer when you need more than one value or a range.

Ranges

For min to max inclusive:

int value = rnd.nextInt(max - min + 1) + min;

The + 1 is the part people get wrong, because nextInt(n) excludes n. A die roll is rnd.nextInt(6) + 1.

Newer code can say it directly:

int value = rnd.nextInt(min, max + 1);

Avoid Math.abs(rnd.nextInt()) % n. It is biased toward smaller values unless n divides evenly into the range, and Math.abs(Integer.MIN_VALUE) is still negative — so it can produce a negative index.

Seeds

Same seed, same sequence:

Random rnd = new Random(42);

This is what makes randomised code testable. Seed it in tests and failures reproduce; leave it unseeded in production. The default seed is derived from a value that varies, so unseeded instances differ.

Creating a new Random() inside a loop is a bug worth naming: instances created in quick succession can pick up related seeds and produce correlated output. Create one and reuse it.

Threads

Random is thread-safe but contended — several threads sharing one instance serialise on it. Use:

ThreadLocalRandom.current().nextInt(100);

Shuffling

Collections.shuffle(list);
Collections.shuffle(list, new Random(42));   // reproducible

Use it rather than writing a shuffle. The obvious hand-rolled version — swap each element with a random other — does not produce a uniform distribution, and the bias is not visible without measuring.

Security

Random is predictable. Given a modest number of outputs, the rest of the sequence can be derived. For tokens, passwords, keys or session identifiers use:

SecureRandom secure = new SecureRandom();

Slower, and the only correct choice when an adversary must not be able to guess the next value.