To generate a random integer in a specific interval [min, max] inclusive in Java, use ThreadLocalRandom.current().nextInt(min, max + 1) for ints, or nextDouble(min, max) for doubles. For older Java versions (before 1.7), use new Random().nextInt(max - min + 1) + min.
Why the Interval Matters: Inclusive vs. Exclusive
Java’s Random class has a subtle but critical behavior: nextInt(bound) returns a value from 0 (inclusive) to bound (exclusive). That means nextInt(10) gives 0–9, never 10. If you want numbers from 1 to 10, you must add 1: nextInt(10) + 1. This off-by-one confusion is the most common source of bugs when generating random numbers in an interval.
For a general inclusive interval [min, max], the formula is nextInt(max - min + 1) + min. The +1 converts the exclusive upper bound to inclusive. For example, to get 5–15 inclusive, you need nextInt(11) + 5, because 15−5+1 = 11.
Modern Approach: ThreadLocalRandom (Java 7+)
Since Java 7, ThreadLocalRandom is the recommended class for most use cases. It provides convenient methods that directly accept min and max bounds, and it avoids contention when multiple threads generate random numbers.
ThreadLocalRandom.current().nextInt(min, max + 1)– inclusive integerThreadLocalRandom.current().nextLong(min, max + 1)– inclusive longThreadLocalRandom.current().nextDouble(min, max)– double, min inclusive, max exclusiveThreadLocalRandom.current().nextFloat()– float 0.0 to 1.0 exclusive
Example: generate a random dice roll (1–6):
int dice = ThreadLocalRandom.current().nextInt(1, 7);
System.out.println(dice);
Note: nextDouble(min, max) returns a value where min is inclusive and max is exclusive. If you need an inclusive upper bound for doubles, you cannot simply add 1; instead, you can use nextDouble(min, max + 1) only if your range is small and you are okay with a slight bias. For most purposes, exclusive upper bound is standard.
Classic Random and Math.random()
Before Java 7, you used java.util.Random:
Random rand = new Random();
int randomInt = rand.nextInt((max - min) + 1) + min;
For doubles, rand.nextDouble() returns 0.0 (inclusive) to 1.0 (exclusive). To scale to [min, max): min + (max - min) * rand.nextDouble().
Another legacy option is Math.random(), which internally uses a static Random instance. It returns a double between 0.0 and 1.0. To get an integer in [min, max]:
int randomInt = (int)(Math.random() * ((max - min) + 1)) + min;
This works but is less readable and slightly slower than ThreadLocalRandom.
How to Choose the Right Method
Your choice depends on your Java version and concurrency needs:
- Java 7 or later, single-threaded: Use
ThreadLocalRandom– it is fast and has the clean min/max API. - Java 7 or later, multi-threaded:
ThreadLocalRandomis still best because each thread gets its own generator, reducing contention. - Java 6 or earlier: Use
new Random()with the formula above. - Need a seed for reproducibility: Use
new Random(seed)so you can recreate the same sequence. - Cryptographic security: Use
SecureRandom(see below).
For most applications, ThreadLocalRandom is the go-to. It is also thread-safe in the sense that each thread has its own instance, so no shared mutable state.
Common Pitfalls and Edge Cases
Several mistakes trip up developers:
- Forgetting the +1 for inclusive upper bound. Always double-check:
nextInt(max - min + 1) + min. - Passing min > max. This throws
IllegalArgumentException. Always validate your bounds. - Using
nextInt(bound)with a negative bound. That also throws an exception. - Assuming
nextDouble(min, max)is inclusive of max. It is not; the upper bound is exclusive. - Creating a new
Randomobject every call. This can lead to identical sequences if the seeds are close in time. Reuse a single instance or useThreadLocalRandom.
Example of a safe inclusive integer method:
public static int randomInt(int min, int max) {
if (min > max) {
throw new IllegalArgumentException("min must be <= max");
}
return ThreadLocalRandom.current().nextInt(min, max + 1);
}
SecureRandom for Security-Sensitive Contexts
If you are generating passwords, tokens, or anything security-related, do not use Random or ThreadLocalRandom—they are not cryptographically secure. Use java.security.SecureRandom:
SecureRandom secureRandom = new SecureRandom();
int secureInt = secureRandom.nextInt(max - min + 1) + min;
SecureRandom uses an unpredictable seed from the OS, making it suitable for cryptographic use. It is slower than Random, so only use it when security matters.
Alternatives: Streams and Third-Party Libraries
Java 8 introduced Random.ints() which can generate streams of random numbers:
Random rand = new Random();
// Generate 5 random integers from 1 to 100 inclusive
rand.ints(5, 1, 101).forEach(System.out::println);
Note that ints(count, min, max) has an exclusive upper bound, so use max + 1 for inclusive. This is handy for bulk generation.
Third-party libraries like Apache Commons Math offer RandomDataGenerator with more distributions, but for simple intervals, the built-in methods are sufficient.
Frequently Asked Questions
How do I generate a random number between 0 and 1?
Use Math.random() or ThreadLocalRandom.current().nextDouble(). Both return a double in [0.0, 1.0). If you need an integer 0 or 1, use ThreadLocalRandom.current().nextInt(2).
Why does nextInt(10) never return 10?
Because the bound is exclusive. The method returns a value from 0 (inclusive) to the bound (exclusive). To get 0–10 inclusive, use nextInt(11).
Can I generate a random boolean?
Yes, use ThreadLocalRandom.current().nextBoolean() or new Random().nextBoolean(). It returns true or false with roughly equal probability.
How do I generate a random number with a specific seed?
Create a Random instance with the seed: new Random(42L). Then call methods on that instance. The same seed produces the same sequence, which is useful for testing.
Is ThreadLocalRandom truly random?
No, it is a pseudorandom number generator (PRNG). It uses a deterministic algorithm, but with a seed that is unpredictable in practice. For most non-security purposes, it is considered random enough.
What is the difference between Random and SecureRandom?
Random is fast but predictable if the seed is known. SecureRandom uses entropy from the OS and is cryptographically secure, but slower. Use SecureRandom for passwords, tokens, and any security-sensitive data.
Related
- Google Sheets Query Multiple Criteria: How-To
- Generate 16 Digit Random Number in Java
- Shortcut for Finding Words? Quick Ways to Search
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Debt Reduction Snowball Spreadsheet: Build One in ExcelA debt reduction snowball spreadsheet lists debts from smallest balance to largest, pays each required minimum, and directs…
- How to Create a Signature Footer in Outlook for EmailTo create a signature footer in Outlook, open the signature settings for your version of Outlook, create and…
- Leave Calendar Template in Excel: Build or DownloadA leave calendar template in Excel can show who is away, on which dates, and whether absences overlap.…
- Can You Undo Remove Duplicates in Excel?Yes. In Excel for Microsoft 365 on Windows, immediately press Ctrl+Z after using Remove Duplicates, or click Undo…
- Word Mail Merge: Keep Excel Formatting for Dates, NumbersWord mail merge does not reliably carry Excel cell formatting into the finished document. To control the result,…
- Random Number 1-100: How to Generate OneThe direct answer: there is no single true random number between 1 and 100 — any number you…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.