Java Create Random Numbers: Methods and Examples

How-to basics · Updated December 3, 2026

To create a random number in Java, use Random for ordinary pseudorandom values, ThreadLocalRandom for many concurrent tasks, or SecureRandom when unpredictability matters for security. For example, new Random().nextInt(10) returns an integer from 0 through 9.

What Java Means by Random

Most random-number APIs in Java generate pseudorandom values: an algorithm produces a sequence that appears random but is determined by an internal state, often initialized from a seed. This is appropriate for simulations, games, randomized tests, and choosing ordinary application values. It is not the same as a guaranteed unpredictable source for passwords or security tokens.

Java’s java.util package provides several useful choices. The best one depends on the range you need, whether multiple threads will generate values, and whether attackers must be unable to predict them. For everyday code, the methods below avoid common range and concurrency mistakes.

Generate Integers with Random

java.util.Random is a familiar general-purpose generator. Its bounded integer method uses an exclusive upper bound: nextInt(bound) returns a value from zero up to, but not including, bound. The bound must be greater than zero.

import java.util.Random;

public class RandomExample {
    public static void main(String[] args) {
        Random random = new Random();

        int value = random.nextInt(10); // 0 through 9
        System.out.println(value);

        int diceRoll = random.nextInt(6) + 1; // 1 through 6
        System.out.println(diceRoll);
    }
}

Create one generator and reuse it rather than constructing a new Random for every value. A newly created generator normally gets an automatically selected seed; supplying a seed makes its sequence repeatable, which is useful for reproducible tests.

Random random = new Random(12345L);
int firstValue = random.nextInt(100);

With the same seed and the same sequence of method calls, the generator produces the same sequence. A fixed seed is therefore useful when a test should be repeatable, but it is unsuitable when the application needs secret, unpredictable values.

Choose a Range or Generate Decimals

For an integer from an inclusive minimum to an inclusive maximum, calculate the width of the range and add the minimum. The following example returns 5 through 15, including both endpoints:

int min = 5;
int max = 15;
int value = random.nextInt(max - min + 1) + min;

This expression assumes that max is at least min and that the range width fits in an int. Validate inputs if the bounds come from users or configuration. For a half-open interval—minimum included, maximum excluded—omit the + 1 in the bound calculation.

Use nextDouble() for a decimal value in the range from 0.0 inclusive to 1.0 exclusive. Scale and shift it to get another interval:

double unitValue = random.nextDouble(); // 0.0 inclusive to 1.0 exclusive

double value = 2.0 + random.nextDouble() * 3.0; // 2.0 inclusive to 5.0 exclusive

For a random boolean, call nextBoolean(). For a random long, use nextLong(); bounded overloads are available in current Java releases, so check the Java version used by the project before relying on newer APIs. Avoid converting a random decimal to an integer by multiplication when an integer method such as nextInt(bound) expresses the intended range more clearly.

Use ThreadLocalRandom for Concurrent Code

java.util.concurrent.ThreadLocalRandom is designed for code where multiple threads need random values. Obtain the generator for the current thread with ThreadLocalRandom.current(). Its bounded methods also use an exclusive upper limit:

import java.util.concurrent.ThreadLocalRandom;

int value = ThreadLocalRandom.current().nextInt(10); // 0 through 9
int between = ThreadLocalRandom.current().nextInt(5, 16); // 5 through 15

The two-bound form includes the origin and excludes the bound, so nextInt(5, 16) can return 15. This API is convenient in parallel or server code because each thread uses its own generator. It is not a cryptographic random-number generator, and it does not provide a way to set a seed for each current-thread instance.

Use SecureRandom for Security-Sensitive Values

For values that protect accounts, sessions, password resets, or cryptographic operations, use java.security.SecureRandom. It is intended to produce values that are difficult for an attacker to predict. Do not substitute Random or ThreadLocalRandom for this purpose, even if their output looks random in a small test.

import java.security.SecureRandom;

SecureRandom secureRandom = new SecureRandom();
byte[] tokenBytes = new byte[32];
secureRandom.nextBytes(tokenBytes);

The byte array contains random bytes; an application that needs a text token must encode those bytes, commonly with a suitable standard encoding such as URL-safe Base64. Keep the resulting token secret and use an adequate token length for the application. Security-sensitive implementations should follow the relevant platform and protocol guidance rather than inventing their own token format.

Normally, let the platform initialize SecureRandom. Do not seed it with a timestamp, a small number, or other predictable data in an attempt to make it “more random”; mishandling seeding can undermine security. When a specific algorithm or provider is required, select it deliberately and follow the deployment environment’s security requirements.

Common Mistakes and Practical Choices

  • Off-by-one ranges: nextInt(10) produces 0–9, not 1–10. Add the lower bound or adjust the bound to match the desired endpoints.
  • Invalid bounds: nextInt(0) throws IllegalArgumentException. Check that a requested range is nonempty before generating a value.
  • Repeatedly creating generators: Keep and reuse a Random, or use ThreadLocalRandom.current() in concurrent code. Avoid relying on rapid repeated construction for distinct values.
  • Confusing repeatability with security: A seed is helpful for reproducing a simulation or test. A predictable seed is not suitable for secrets.
  • Assuming equal probabilities after custom mapping: Methods such as taking a remainder with % can introduce bias when the source range is not an exact multiple of the target range. Prefer a bounded API such as nextInt(bound).

In short, use Random for straightforward, non-security-sensitive code; ThreadLocalRandom for concurrent ordinary generation; and SecureRandom for security-sensitive bytes or values. If repeatable results matter, use a seeded pseudorandom generator in test or simulation code and document that choice.

Frequently Asked Questions

How do I generate a random number from 1 to 100 in Java?
Use random.nextInt(100) + 1. The bounded call returns 0–99, and adding one shifts the result to 1–100.

How do I generate a random number between two values?
For an inclusive integer range from min to max, use random.nextInt(max - min + 1) + min, after checking the bounds. With ThreadLocalRandom, use ThreadLocalRandom.current().nextInt(min, max + 1) for the same endpoints, provided the calculation does not overflow.

How do I get a random decimal in Java?
Call nextDouble() for a value from 0.0 inclusive to 1.0 exclusive. To scale it to a range, multiply by the range width and add the lower endpoint.

Is Java Random truly random?
Random is pseudorandom: its algorithm produces a repeatable sequence from its seed. That is usually enough for ordinary program behavior, but it is not designed to protect secrets from prediction.

Which Java random class should I use?
Choose Random for simple general-purpose values, ThreadLocalRandom for concurrent non-security work, and SecureRandom for tokens or other security-sensitive values.

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.