In Java, you generate random numbers using java.util.Random, Math.random(), or ThreadLocalRandom (for concurrency). The simplest one-liner is new Random().nextInt(100) for an integer between 0 and 99, or Math.random() * 100 for a double between 0.0 and 100.0. This article explains each approach, how to choose, common pitfalls, and practical examples.
Why Java Has Multiple Random Number Generators
Java provides several random number generation classes because different use cases have different requirements. The core java.util.Random class, introduced in Java 1.0, uses a linear congruential generator (LCG) that is fast and adequate for most non-cryptographic tasks. Math.random() is a static method that internally uses a single Random instance, making it convenient but not thread-safe. For concurrent programs, ThreadLocalRandom (since Java 7) gives each thread its own generator, reducing contention. For cryptographic security, java.security.SecureRandom is the correct choice because it uses an unpredictable seed source.
How to Use java.util.Random
The Random class offers methods to generate primitive types. You create an instance and call its methods:
nextInt()– returns any int (including negative values).nextInt(int bound)– returns an int from 0 (inclusive) to bound (exclusive).nextDouble()– returns a double from 0.0 (inclusive) to 1.0 (exclusive).nextFloat()– returns a float from 0.0 to 1.0.nextLong()– returns a long.nextBoolean()– returns true or false.
Example: generate a random number between 1 and 6 (like a die):
Random rand = new Random();
int dieRoll = rand.nextInt(6) + 1; // 1-6
If you need a random integer in a range like 10 to 20, use rand.nextInt(11) + 10 because the bound is exclusive and the offset shifts the range.
Using Math.random() for Quick Doubles
Math.random() returns a double from 0.0 to 1.0 (exclusive). To get a random integer, you multiply and cast: (int)(Math.random() * 100) gives 0 to 99. To get a range, use (int)(Math.random() * (max - min + 1)) + min. For example, a random number from 5 to 15: int r = (int)(Math.random() * 11) + 5;. This method is simple but not ideal for high-frequency calls because it uses a shared generator that can become a bottleneck in multithreaded code.
ThreadLocalRandom for Concurrent Applications
When multiple threads generate random numbers, using a single Random instance causes contention. ThreadLocalRandom solves this by giving each thread its own generator. It also has a more modern API: ThreadLocalRandom.current().nextInt(bound) or nextInt(origin, bound) for a range. Example:
int randomInRange = ThreadLocalRandom.current().nextInt(100, 200); // 100-199
This class is preferred in parallel streams and multithreaded servers. It is not instantiated with new; you call current().
SecureRandom for Cryptography and Passwords
If you generate passwords, tokens, or anything security-sensitive, use SecureRandom. It uses an entropy source (like /dev/urandom on Linux) to produce unpredictable values. Example:
SecureRandom secureRand = new SecureRandom();
byte[] bytes = new byte[16];
secureRand.nextBytes(bytes);
This is slower than Random but necessary for security. Never use Random for cryptographic keys or session IDs because its seed is predictable.
Common Pitfalls and Misconceptions
One common mistake is using new Random(seed) with a fixed seed in production code – that produces the same sequence every run, which is useful for testing but not for real randomness. Another pitfall is using nextInt() without a bound and then taking the modulo to get a range, which introduces bias for certain bounds. For example, Math.abs(rand.nextInt()) % 100 can produce non-uniform results because the number of possible int values is not divisible by 100. Always use nextInt(bound) or nextInt(origin, bound).
Another misconception: Math.random() is not thread-safe, but it is also not broken – it just uses a shared instance that may cause performance issues. Also, Random is not cryptographically secure; if you need security, use SecureRandom.
How to Choose the Right Generator
Consider your use case:
- Casual games, simulations, sampling –
RandomorMath.random(). - Multithreaded code –
ThreadLocalRandom. - Cryptography, passwords, tokens –
SecureRandom. - Testing with reproducible results –
new Random(fixedSeed).
For most applications, ThreadLocalRandom is a good default because it works well in single-threaded and multithreaded contexts.
Frequently Asked Questions
How do I generate a random number between 1 and 100? Use new Random().nextInt(100) + 1 for an int, or (int)(Math.random() * 100) + 1.
Can I generate a random double in a specific range? Yes: ThreadLocalRandom.current().nextDouble(min, max) gives a double from min (inclusive) to max (exclusive). For Random, use min + (max - min) * rand.nextDouble().
Is Math.random() deprecated? No, it is still supported, but many developers prefer ThreadLocalRandom for its clearer API and better concurrency.
Why does my random sequence repeat every run? You likely used new Random(seed) with a constant seed. To get different sequences, use the no-arg constructor, which seeds from the system time.
Can I use Random for a lottery number generator? Yes, for non-security purposes. Use nextInt(49) + 1 for numbers 1-49, but ensure you handle duplicates if needed.
What is the difference between nextInt(100) and nextInt() % 100? nextInt(100) is uniform and unbiased. nextInt() % 100 is biased because the range of int is not a multiple of 100, so some remainders occur more often.
Related
- Google Sheets Sum Unique Values: 3 Easy Formulas
- Holiday Calendar Template Excel: Free & How to Use
- Standard Chartered Balance Sheet: Key Facts
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 Add Page Numbers in ExcelTo add page numbers in Excel for Microsoft 365 on Windows, open the worksheet in Page Layout view,…
- 911 Dispatch Data Entry Practice Test: 10 DrillsThis listicle covers ten specific 911 dispatch data entry practice tests and drills, from full simulation platforms to…
- How to Indent Bullet Points in ExcelTo indent a bullet point in Excel, put a bullet character at the start of a cell’s text,…
- Row Grouping in Excel: Collapse and Expand RowsTo group rows in Excel for Microsoft 365 on Windows, select the row numbers you want to organize,…
- Bulls Eye 1-2-3 Data Sheet: Specs, Uses and SafetyThe Bulls Eye 1-2-3 data sheet is the manufacturer’s technical document for a specific Zinsser primer product; find…
- How to Make a Fillable Form in Word 365To make a fillable form in Word 365, add content controls from the Developer tab, set up each…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.