Java Code to Generate Random Number

How-to basics · Updated November 23, 2026

To generate a random number in Java, use ThreadLocalRandom.current().nextInt() for integers, nextDouble() for decimals, or new Random().nextInt(bound) for a simpler one-off. For example, int randomNum = ThreadLocalRandom.current().nextInt(1, 101); gives a number from 1 to 100 inclusive. This article explains the main methods, how to choose between them, common pitfalls, and answers frequent questions.

Background: Java’s Random Number Generators

Java has several classes for generating pseudo-random numbers, each with different strengths. The oldest is java.util.Random, introduced in Java 1.0. It uses a linear congruential formula and is thread-safe but can be slow under high concurrency due to locking. In Java 7, java.util.concurrent.ThreadLocalRandom was added, which uses a per-thread seed and avoids contention, making it faster in multi-threaded programs. Java 8 added java.util.SplittableRandom for parallel streams, and Java 17 introduced java.util.random.RandomGenerator as a unified interface. For most everyday needs, ThreadLocalRandom is the recommended choice.

How It Works: The Core Methods

All random generators in Java produce sequences of numbers that appear random but are actually deterministic, based on a seed value. If you create a Random object with the same seed, you get the same sequence. Here are the most common methods:

  • nextInt() – returns any int (including negative values).
  • nextInt(bound) – returns an int from 0 (inclusive) to bound (exclusive). For example, nextInt(10) gives 0–9.
  • nextInt(origin, bound) – available in ThreadLocalRandom and RandomGenerator, returns from origin (inclusive) to bound (exclusive).
  • nextDouble() – returns a double from 0.0 (inclusive) to 1.0 (exclusive).
  • nextDouble(origin, bound) – returns a double in a custom range.
  • nextBoolean() – returns true or false.

Example: To simulate a dice roll (1 to 6), use ThreadLocalRandom.current().nextInt(1, 7) – note the upper bound is exclusive, so 7 makes 6 possible.

How to Choose: Which Class to Use

Your choice depends on your use case:

  • Single-threaded programs – ThreadLocalRandom is fine and slightly faster than Random.
  • Multi-threaded programs – ThreadLocalRandom avoids contention; each thread has its own generator.
  • Cryptographic security – use java.security.SecureRandom for passwords, tokens, or anything security-related. It uses a secure algorithm (e.g., SHA1PRNG) and is slower but unpredictable.
  • Parallel streams – use RandomGenerator with Stream.generate() or IntStream methods.
  • Reproducible tests – use new Random(seed) to get the same sequence every run.

For most applications, ThreadLocalRandom.current() is the best default because it is fast, simple, and does not require creating a new object each time.

Common Problems and Misconceptions

One frequent mistake is using Math.random() for integer ranges. Math.random() returns a double from 0.0 to 1.0, so to get an integer you must multiply and cast: (int)(Math.random() * 10) gives 0–9. However, this can introduce bias if the range is not a power of two, and it is less readable. Prefer nextInt(bound).

Another misconception is that nextInt(bound) includes the bound. It does not – the upper bound is exclusive. Always remember: nextInt(1, 11) gives 1–10, not 11.

A third issue is creating a new Random object every time you need a number. That is wasteful; instead, reuse a single instance or use ThreadLocalRandom.current() which is a static method returning a per-thread instance.

Finally, do not use Random for security-sensitive data. Its algorithm is predictable if the seed is known, and even without the seed, it is not cryptographically secure. Always use SecureRandom for passwords, session IDs, or encryption keys.

Comparing Random, ThreadLocalRandom, and SecureRandom

Here is a quick comparison:

  • Random – thread-safe, but contention slows down concurrent use. Good for simple, single-threaded code.
  • ThreadLocalRandom – not thread-safe by itself, but each thread gets its own instance, so no contention. Faster in concurrent scenarios. Cannot set a seed (except in Java 8+ via setSeed which is discouraged).
  • SecureRandom – uses a cryptographically strong algorithm. Slower, but unpredictable. Use for security.

For example, in a web server handling many requests, using Random across threads can become a bottleneck. Switching to ThreadLocalRandom often improves performance without changing logic.

Cost and Performance Considerations

Generating random numbers is extremely cheap – typically a few nanoseconds per call. The main cost is object creation if you instantiate a new Random each time. That is why reusing or using ThreadLocalRandom.current() is recommended. SecureRandom is significantly slower (microseconds) because it gathers entropy from the OS. For most non-security uses, the performance difference is negligible, but in tight loops, avoid SecureRandom unless needed.

Safety and Security Notes

If you generate random numbers for security purposes – such as reset tokens, API keys, or password salts – always use SecureRandom. Never use Random or Math.random() for these, as an attacker could predict the sequence if they know the seed or observe outputs. Also, when using SecureRandom, do not set a seed manually; let it self-seed from the OS. For non-security uses, there are no safety concerns beyond avoiding negative numbers or overflow when specifying bounds – ensure your bound is positive and greater than the origin.

Alternatives: Third-Party Libraries

Java’s built-in generators cover almost all needs. However, if you need higher-quality randomness for simulations (e.g., Monte Carlo methods), you might consider the org.apache.commons.math3.random package from Apache Commons Math, which offers generators like MersenneTwister. For cryptographic strength, Java’s SecureRandom is sufficient. For most developers, sticking with the standard library is simpler and avoids extra dependencies.

Frequently Asked Questions

How do I generate a random number between 1 and 100? Use ThreadLocalRandom.current().nextInt(1, 101) – the upper bound is exclusive, so 101 makes 100 possible.

Can I generate a random double between 0 and 1? Yes, Math.random() does exactly that, or ThreadLocalRandom.current().nextDouble() which is more consistent.

Is Math.random() deprecated? No, it is still valid, but ThreadLocalRandom is preferred for new code because it is more flexible and avoids casting.

How do I generate a random boolean? Use ThreadLocalRandom.current().nextBoolean() or new Random().nextBoolean().

Can I set a seed to get the same random sequence? Yes, with new Random(seed) or new RandomGenerator(seed) (Java 17+). This is useful for testing.

What is the difference between nextInt() and nextInt(bound)? nextInt() returns any int (including negative), while nextInt(bound) returns from 0 to bound-1. Use the bound version for ranges.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.