Java Program to Generate Random Number: 4 Ways

How-to basics · Updated November 23, 2026

The simplest way to generate a random integer in Java is new Random().nextInt(max), which returns a number from 0 (inclusive) to max (exclusive). For a random double between 0.0 and 1.0, use Math.random(). This article covers those basics plus the more powerful ThreadLocalRandom and SecureRandom classes, with working examples and guidance on when each is appropriate.

Why Java Has Multiple Random Generators

Java’s standard library includes several random number generators because “random” means different things in different contexts. The original java.util.Random (since Java 1.0) uses a linear congruential formula—fast but predictable if you know the seed. Math.random() is a thin wrapper around a single shared Random instance. Later versions added ThreadLocalRandom for better concurrency and SecureRandom for cryptographic security. Each trades speed, thread-safety, and unpredictability differently.

The Core Classes and Their Differences

  • java.util.Random – the classic, thread-safe (synchronized) generator. Good for most non-concurrent needs.
  • Math.random() – returns a double between 0.0 and 1.0. Internally uses Random but simpler to call.
  • java.util.concurrent.ThreadLocalRandom – faster in multi-threaded programs because each thread gets its own generator, no contention. Available since Java 7.
  • java.security.SecureRandom – produces cryptographically strong random numbers, suitable for passwords, tokens, or session IDs.

For most everyday tasks—simulations, games, tests—Random or ThreadLocalRandom suffice. Only use SecureRandom when security matters.

Basic Examples: Random Integers and Doubles

Here is a complete program that prints three random integers between 1 and 10 (inclusive):

import java.util.Random;

public class RandomDemo {
    public static void main(String[] args) {
        Random rand = new Random();
        // nextInt(10) gives 0-9, so add 1 for 1-10
        int a = rand.nextInt(10) + 1;
        int b = rand.nextInt(10) + 1;
        int c = rand.nextInt(10) + 1;
        System.out.println(a + " " + b + " " + c);
    }
}

To get a random double between 0.0 (inclusive) and 1.0 (exclusive), use Math.random() directly:

double d = Math.random();

To get a double in a specific range, say 5.0 to 10.0, multiply and add:

double range = 5.0 + Math.random() * 5.0; // 5.0 to 10.0

How to Choose a Range Correctly

The most common mistake is off-by-one errors because nextInt(n) is exclusive of n. If you want numbers from 1 to 6 (like a die), use rand.nextInt(6) + 1. If you want 0 to 100 inclusive, use rand.nextInt(101). For a range from min to max inclusive, the formula is:

int randomNum = rand.nextInt((max - min) + 1) + min;

For example, with min=10 and max=20, nextInt(11) + 10 yields 10 through 20. For floating-point ranges, use min + (max - min) * rand.nextDouble(), which includes min but excludes max.

ThreadLocalRandom for Concurrent Programs

If multiple threads call Random concurrently, they contend on a shared lock, slowing things down. ThreadLocalRandom avoids this by giving each thread its own generator. Its API is slightly different—you do not instantiate it; you call the static method:

import java.util.concurrent.ThreadLocalRandom;

int die = ThreadLocalRandom.current().nextInt(1, 7); // 1 to 6
long big = ThreadLocalRandom.current().nextLong(1_000_000L, 2_000_000L);
double rate = ThreadLocalRandom.current().nextDouble(0.5, 1.5);

Notice that nextInt(min, max) here is inclusive of min and exclusive of max, which is more intuitive than Random‘s single-argument version. This class is the recommended choice for any multi-threaded application, including parallel streams.

SecureRandom for Passwords and Tokens

Using Random for security-sensitive values is dangerous because its output is predictable if an attacker knows the seed or observes enough output. SecureRandom uses an algorithm like SHA1PRNG or the operating system’s entropy source. Example:

import java.security.SecureRandom;

SecureRandom secure = new SecureRandom();
byte[] bytes = new byte[16];
secure.nextBytes(bytes); // fills with random bytes
int token = secure.nextInt(1000000); // random 0-999999

Use this for generating API keys, password salts, or session identifiers. It is slower than Random but that is a fair trade for security.

Common Pitfalls and Misconceptions

  • Seeding with the same value gives the same sequence. If you create new Random(42) twice, you get identical numbers. That is useful for reproducible tests but surprising in production.
  • Math.random() is not thread-safe? Actually it is, because it uses a shared Random instance that is synchronized. But that synchronization can be a bottleneck.
  • Random does not produce truly random numbers. It is pseudo-random—deterministic given the seed. For most purposes that is fine.
  • Do not use new Random() inside a loop. Creating a new instance each iteration wastes time and can produce repeated values if the seeds are close in time. Create one instance outside the loop.

Frequently Asked Questions

How do I generate a random number between 1 and 100 in Java?

Use new Random().nextInt(100) + 1. The nextInt(100) returns 0-99, adding 1 shifts to 1-100. For a range like 5 to 15, use nextInt(11) + 5.

What is the difference between Math.random() and Random?

Math.random() is a static method that always returns a double between 0.0 and 1.0. It is a convenience wrapper around a single Random instance. The Random class gives you more control: you can create multiple instances, set seeds, and directly get integers, longs, floats, and booleans.

Can I generate a random boolean in Java?

Yes. new Random().nextBoolean() returns true or false with roughly equal probability. ThreadLocalRandom.current().nextBoolean() also works.

Is SecureRandom slower than Random?

Yes, typically by a factor of 10 to 100 depending on the platform, because it gathers entropy from the operating system and performs more complex calculations. Use it only for security-critical data, not for simulations or games.

How do I generate a random number without repeating previous ones?

There is no built-in method for that. You can store generated numbers in a Set and loop until you find a new one, or shuffle a list of all possible values using Collections.shuffle(). For example, to get unique numbers from 1 to 10, create a list, shuffle it, and take the first few.

What does the seed parameter do in Random?

The seed is the starting point for the pseudo-random sequence. If you use the same seed, you get the same sequence of numbers. This is useful for debugging or reproducible experiments. If you do not provide a seed, Java uses the current time in nanoseconds, so each run differs.

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.