Skip to content
Tutorials Center
My learning

Topics

Lesson 109 of 201 Β· Working with Data

Random Numbers

Generate random numbers in Java with Random, ThreadLocalRandom and RandomGenerator, make results repeatable with seeds, use SecureRandom for tokens, and shuffle and sample.

Games roll dice, simulations model traffic, tests generate sample data, load balancers pick a server, and web apps create password-reset tokens. All of them need random numbers, but not all of them need the same kind. A dice game needs numbers that look random and arrive fast. A test needs "random" data that is exactly the same on every run so a failure can be reproduced. A reset token needs numbers that no attacker can predict, even after seeing thousands of earlier tokens.

Java has a tool for each job: java.util.Random, ThreadLocalRandom, the RandomGenerator family (Java 17) and java.security.SecureRandom. This lesson shows how to get numbers in exactly the range you want, how seeds make results reproducible, which generator to use when, and how to shuffle, sample and pick weighted choices correctly. The quick overview in The Math Class introduced the names; here you'll learn to use them like a professional.

Pseudo-random numbers

Computers are deterministic machines, so ordinary generators are pseudo-random: they start from an internal number called the seed and apply a formula to produce the next value, then the next, and so on. The sequence passes statistical tests for randomness, but it is completely determined by the seed. Two generators with the same seed and the same algorithm produce the same sequence forever.

That's a feature, not a flaw. It's what makes simulations and tests repeatable. It only becomes a problem when someone can benefit from predicting the next value, which is why security code uses a different generator (see SecureRandom below).

java.util.Random

Random is the classic generator and still the one you'll see most often. Create one and ask it for values:

Java The main Random methods

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Run it a few times; every line changes. The details worth memorizing:

  • Bounds are half-open: the origin is included and the bound is excluded. nextInt(10) returns 0 to 9, nextInt(1, 7) returns 1 to 6, nextDouble() returns values from 0.0 up to, but never exactly, 1.0.
  • nextInt(origin, bound), nextLong(origin, bound), nextDouble(origin, bound) and nextGaussian(mean, stddev) came with Java 17's RandomGenerator interface. Older code computes ranges by hand, like random.nextInt(6) + 1.
  • A bound that isn't positive (or an origin that isn't smaller than the bound) throws IllegalArgumentException.
  • nextGaussian() follows a normal distribution: values near the mean are common, values far away are rare. Use it for natural quantities like heights or measurement noise.

Don't build ranges with % or Math.abs

Before Java 17 you'll often see this pattern for "a number from 0 to nβˆ’1":

Java
int index = Math.abs(random.nextInt()) % n;   // two bugs in one line

It has two problems. First, Math.abs(Integer.MIN_VALUE) is still Integer.MIN_VALUE (negative), because +2,147,483,648 doesn't fit in an int, so about once in four billion calls you get a negative index. Second, % introduces modulo bias: unless n divides 2Β³Β² evenly, some results come up slightly more often than others. nextInt(n) and nextInt(origin, bound) are carefully written to avoid both problems, so always use them.

Seeds and reproducibility

Pass a seed to the constructor and the sequence becomes fixed. The algorithm of java.util.Random is spelled out in its documentation, so a given seed gives the same numbers on every JVM, every operating system and every Java version:

Java Same seed, same sequence

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Press Run as often as you like: the output never changes, and the two 2024 lines are identical. That makes seeds perfect for:

  • Tests that use generated data. If a test fails, the same seed reproduces the failure exactly. A good habit is to pick a random seed, print it, and allow overriding it, so a failing run can be replayed.
  • Simulations and games where a "world seed" recreates the same map or level.
  • Experiments whose results others need to verify.

new Random() without a seed picks one that is different on every call (it mixes the current time with a counter), which is what you want in production.

A seed isn't a secret. If a password generator used new Random(System.currentTimeMillis()), an attacker who knows roughly when the password was made could try every millisecond in that window and regenerate it. Even without knowing the seed, Random's internal state can be recovered from just two consecutive nextInt() outputs. Never use Random, ThreadLocalRandom or Math.random() for anything security-related.

ThreadLocalRandom for concurrent code

A single Random object is thread-safe, but every call updates one shared internal value with an atomic operation. When many threads hammer the same instance, they slow each other down. ThreadLocalRandom gives each thread its own generator, with no sharing at all:

Java Random numbers from several threads

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Always call ThreadLocalRandom.current() in the thread that uses it, as above, and don't store the result in a shared field or pass it to another thread. ThreadLocalRandom can't be seeded (setSeed throws UnsupportedOperationException), so use it for speed, not for reproducibility. Threads themselves are covered in Threads.

RandomGenerator: the modern interface

Java 17 added the java.util.random package. Its core is the RandomGenerator interface, which Random, ThreadLocalRandom, SplittableRandom and SecureRandom all implement, plus a set of newer algorithms with better statistical quality than the 1990s-era formula inside Random:

Java Choosing an algorithm with RandomGenerator

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Practical advice:

  • Write methods that accept a RandomGenerator parameter. Then production code can pass RandomGenerator.getDefault(), tests can pass a seeded generator, and security code can pass a SecureRandom, without changing the method.
  • RandomGenerator.getDefault() currently returns an L32X64MixRandom, a fast, high-quality generator. The exact algorithm may change in future versions, so if you store seeds to reproduce results later, name the algorithm explicitly with RandomGeneratorFactory.of("...").
  • In the list, the number of state bits is a rough guide to quality: more state means a longer period before the sequence repeats. Random has only 48 bits. SecureRandom reports Integer.MAX_VALUE because its state isn't a fixed-size number; it keeps drawing fresh entropy.
  • Every generator can produce streams: ints(count, origin, bound), longs(...), doubles(...). They're handy with Streams.
  • Some algorithms are "splittable" or "jumpable", which lets you create many independent generators for parallel work. That matters for large simulations; most programs never need it.

java.security.SecureRandom is a cryptographically strong generator. Its output is drawn from the operating system's entropy sources and mixed so that seeing previous values tells an attacker nothing about the next ones. It's slower than Random, but for tokens, passwords, keys, salts and session IDs, it's the only correct choice:

Java Tokens, codes and passwords with SecureRandom

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Guidelines that prevent real-world bugs:

  • Create one SecureRandom and reuse it. It's thread-safe, and creating many instances is wasteful.
  • Don't seed it yourself. Calling setSeed with a fixed value on some implementations makes the output predictable. Let it seed itself.
  • SecureRandom.getInstanceStrong() returns the strongest available generator. On some systems it can block while waiting for entropy, so it's meant for long-term keys, not for every web request. Plain new SecureRandom() is right for tokens.
  • Generate at least 128 bits (16 bytes) for tokens; 32 bytes is a common choice. The token is then encoded as hex or Base64 to make it printable, as covered in UUIDs, Hashing and Base64.
  • The password alphabet above leaves out look-alike characters (0/O, 1/l/I), a small kindness for anyone who has to type it.

Shuffling and sampling

Many "random" tasks are really about choosing or reordering items. Collections.shuffle does a correct Fisher–Yates shuffle, in which every ordering is equally likely. Pass your own generator to make the shuffle reproducible:

Java Shuffle, pick, sample and weighted choice

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A few notes on this example:

  • Collections.shuffle(list, random) accepts any RandomGenerator since Java 21; on older versions it needs a Random. Without the second argument it uses an internal generator you can't seed.
  • List.of(...) is immutable, so the code shuffles a copy in an ArrayList. Shuffling the original would throw UnsupportedOperationException.
  • sample picks items without replacement (no duplicates). For huge lists where k is tiny, shuffling everything is wasteful; pick random indexes into a Set until it has k of them instead.
  • The weighted pick draws a "ticket" in the total range and walks through the weights. With weights 70/25/5 the counts land close to 7,000, 2,500 and 500.
  • Because the generator is seeded with 42, every line of output is the same on every run.

To shuffle an array, there's no Arrays.shuffle; either wrap it with Arrays.asList (for object arrays) and shuffle that view, or write the classic loop: for i from the last index down to 1, swap element i with element random.nextInt(i + 1).

Which generator should I use?

Situation Use
Quick one-off value in a small program Math.random() or RandomGenerator.getDefault()
Games, simulations, shuffling RandomGenerator.getDefault() or new Random()
Repeatable tests and experiments new Random(seed) or RandomGeneratorFactory.of(name).create(seed)
Many threads generating values ThreadLocalRandom.current()
Tokens, passwords, keys, salts, IDs that must be unguessable new SecureRandom()

Math.random() is just a shortcut to a shared Random that returns a double from 0.0 to 1.0. It's fine for a quick experiment but awkward for anything else, since you have to multiply, cast and add to get a range.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. Which call returns a value from 1 to 6, both included?

    The bound is exclusive, so nextInt(1, 7) produces 1 through 6. nextInt(1, 6) never returns 6, nextInt(6) returns 0 to 5, and nextInt(7) - 1 returns -1 to 5.
  2. 2. Two programs each create new Random(500) and call nextInt(100) ten times. What do they print?

    The algorithm of java.util.Random is fully specified, so the same seed always yields the same sequence, regardless of platform or Java version.
  3. 3. You need tokens for password-reset emails. Which is correct?

    Only SecureRandom is designed to be unpredictable to attackers. Seeds based on time can be guessed, and Random's state can be recovered from its outputs.
  4. 4. What is wrong with Math.abs(random.nextInt()) % n as a random index?

    Math.abs(Integer.MIN_VALUE) stays negative, and the remainder introduces modulo bias. nextInt(n) avoids both problems.
  5. 5. Why does this throw? Collections.shuffle(List.of(1, 2, 3), new Random())

    shuffle reorders the list in place, so an immutable list throws UnsupportedOperationException. Copy it into an ArrayList first.

Summary

  • Ordinary generators are pseudo-random: a seed fully determines the sequence. new Random(seed) is reproducible everywhere; new Random() picks a fresh seed.
  • Use nextInt(origin, bound) and friends (Java 17) for ranges; the bound is exclusive. Avoid Math.abs(nextInt()) % n.
  • ThreadLocalRandom.current() is the fast choice for concurrent code; it can't be seeded.
  • RandomGenerator is the common interface (Java 17). Accept it as a parameter, use getDefault() for general work, and name an algorithm with RandomGeneratorFactory when you store seeds.
  • SecureRandom is the only correct generator for tokens, passwords, keys and salts. Create one, reuse it, and don't seed it.
  • Collections.shuffle(list, generator) shuffles fairly; shuffle a copy to sample without replacement, and walk cumulative weights for weighted choices.

Next: UUIDs, Hashing and Base64, where you'll turn random bytes and data into unique IDs, fingerprints and printable text.