To generate a random integer in a specific range in Java, use ThreadLocalRandom.current().nextInt(min, max + 1) for inclusive bounds, or Random.nextInt(max - min) + min for the classic approach. For a double in a range, use ThreadLocalRandom.current().nextDouble(min, max).
Why the Range Question Is Trickier Than It Looks
Java’s built-in random generators produce numbers starting at 0, not at an arbitrary minimum. The nextInt(n) method returns a value from 0 (inclusive) to n (exclusive). So to get a range like 5 to 15, you must shift the result by adding the minimum. The common mistake is forgetting that the upper bound is exclusive, which leads to off-by-one errors. For example, new Random().nextInt(10) gives 0–9, not 0–10.
Three Ways to Generate a Random Integer in a Range
Java offers several APIs, each with slightly different behavior. Choose based on your Java version and concurrency needs.
- Java 1.7+ –
ThreadLocalRandom(recommended for most cases):ThreadLocalRandom.current().nextInt(min, max + 1)gives an inclusive min and inclusive max. It also hasnextLong(min, max)andnextDouble(min, max). - Java 1.0+ –
java.util.Random:new Random().nextInt(max - min + 1) + minyields a value from min to max inclusive. For exclusive max, drop the+1. - Java 17+ –
RandomGeneratorinterface:RandomGenerator.getDefault().nextInt(min, max + 1)works the same as ThreadLocalRandom, but allows plugging in different generators likeSplittableRandom.
Generating Random Doubles and Floats in a Range
For floating-point numbers, the logic is similar but the upper bound is usually exclusive. ThreadLocalRandom.current().nextDouble(min, max) returns a double from min (inclusive) to max (exclusive). If you need a float, cast the result: (float) ThreadLocalRandom.current().nextDouble(min, max). The older Random.nextDouble() returns 0.0 to 1.0, so to map it to a range: min + (max - min) * random.nextDouble(). This works for any double range, including negative values.
How to Choose the Right Random Class
The main factors are thread safety, performance, and Java version.
- Single-threaded code –
java.util.Randomis fine and simple. - Multi-threaded code –
ThreadLocalRandomavoids contention because each thread gets its own generator. Using a sharedRandominstance across threads can cause performance bottlenecks. - Cryptographic security – For passwords, tokens, or anything security-sensitive, use
SecureRandom(fromjava.security). It is slower but unpredictable. - High-performance parallel streams –
SplittableRandomis designed for fork/join and parallel streams. It is faster thanRandombut not thread-safe.
Common Pitfalls and How to Avoid Them
Even experienced developers hit these issues:
- Off-by-one errors:
nextInt(max)never returns max. To include max, add 1 to the bound or use the two-argument version. - Negative ranges: The formula
nextInt(max - min + 1) + minworks with negative min, e.g., min = -5, max = 5 gives -5 to 5. - Using
Math.random()incorrectly:Math.random()returns a double 0.0 to 1.0. To get an integer, you must multiply and cast:(int)(Math.random() * (max - min + 1)) + min. Forgetting the cast truncates to 0. - Creating a new
Randomobject each call: This can produce identical numbers if created too quickly, because the seed is based on time. Reuse one instance. - Not checking bounds for
nextIntwith negative arguments:Random.nextInt(int bound)throwsIllegalArgumentExceptionif bound is zero or negative. Always ensure the range is positive.
Complete Code Example with Output
Here is a full program that generates a random integer between 1 and 10 (inclusive) using three methods:
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
public class RandomRangeExample {
public static void main(String[] args) {
int min = 1;
int max = 10;
// Method 1: ThreadLocalRandom (Java 7+)
int r1 = ThreadLocalRandom.current().nextInt(min, max + 1);
// Method 2: java.util.Random
Random rand = new Random();
int r2 = rand.nextInt(max - min + 1) + min;
// Method 3: Math.random()
int r3 = (int)(Math.random() * (max - min + 1)) + min;
System.out.println("ThreadLocalRandom: " + r1);
System.out.println("Random: " + r2);
System.out.println("Math.random: " + r3);
}
}
Each run prints three different numbers, all between 1 and 10. This example assumes you have a Java development environment set up; compile with javac RandomRangeExample.java and run with java RandomRangeExample.
Performance and Thread Safety Considerations
If you are generating many random numbers, the choice of generator matters. ThreadLocalRandom is generally faster than Random in multi-threaded scenarios because it avoids locking. In single-threaded code, Random is slightly faster than ThreadLocalRandom due to lower overhead. SecureRandom is significantly slower—use it only when security is required. For parallel streams, ThreadLocalRandom is not directly usable; use SplittableRandom or RandomGenerator with a stream source.
Frequently Asked Questions
How do I generate a random number between 1 and 100 in Java?
Use ThreadLocalRandom.current().nextInt(1, 101) for inclusive 1–100. Or new Random().nextInt(100) + 1 (since nextInt(100) gives 0–99, adding 1 gives 1–100).
Is Math.random() the same as Random?
No. Math.random() internally uses a static Random instance, but it returns a double between 0.0 and 1.0. You must scale and cast to get an integer. Random provides direct integer methods and is more flexible.
Can I generate a random number in a range without using Random?
Yes, you can use Math.random() or, in Java 17+, the RandomGenerator interface with a custom implementation. But ThreadLocalRandom is the simplest modern way.
Why does nextInt(10) never return 10?
Because the upper bound is exclusive. The method returns values from 0 (inclusive) to 10 (exclusive), so the maximum is 9. To include 10, use nextInt(11) or nextInt(0, 11).
How do I generate a random boolean?
Use ThreadLocalRandom.current().nextBoolean() or new Random().nextBoolean(). It returns true or false with roughly equal probability.
Is there a way to generate a random number in a range without creating a new object every time?
Yes, store a single Random or ThreadLocalRandom instance in a static field or use ThreadLocalRandom.current() which is thread-local and does not require manual creation. Reusing an instance avoids seeding issues.
Final Tips for Production Code
For most applications, ThreadLocalRandom is the best default. It is simple, thread-safe, and performs well. Always double-check your bounds: if you need a number from min to max inclusive, use nextInt(min, max + 1). If you need exclusive max, omit the +1. For security-sensitive contexts, never use Random or ThreadLocalRandom—use SecureRandom. Finally, test your range logic with edge cases like min = 0, max = 1, or negative values to ensure the formula behaves as expected.
Related
- Node.js Generate Random 6 Digit Number: 3 Ways
- Project Firewood Table Lamp: Build Guide & Ideas
- Google Sheets Prevent Duplicates in Column?
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Find Repeat Names in Excel Quickly and ClearlyTo find repeat names in Excel, select the name cells and choose Home > Conditional Formatting > Highlight…
- How to Get Rid of All Track Changes in Microsoft WordTo get rid of tracked changes in Word, choose whether to keep or discard the proposed edits, then…
- Excel Get Data From a Semantic Model: Connect and AnalyzeYes. In Excel for Microsoft 365 on Windows, connect to a Power BI semantic model through Data >…
- How to Split in Onshape: Parts, Faces, and SketchesTo split a solid in Onshape, open a Part Studio, choose Split from the feature toolbar, select the…
- How to Copy Selected Cells in Excel Without ErrorsTo copy selected cells in Excel for Microsoft 365 on Windows, select a cell or range, press Ctrl+C,…
- Excel Cell Service in Clementi: What to CheckIf you mean a mobile-phone repair or service business called Excel Cell Service, I can’t reliably confirm that…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.