To generate a random number in Java, use ThreadLocalRandom.current().nextInt() for integers, nextDouble() for decimals, or the older Math.random() for a double between 0.0 and 1.0. For most applications, ThreadLocalRandom is the simplest and most efficient choice.
Background: Java’s Randomness Tools
Java offers several ways to produce random numbers, each with different strengths. The core classes live in java.util and java.util.concurrent. The main options are:
Math.random()– a static method returning adoublein [0.0, 1.0).java.util.Random– a class with methods likenextInt(),nextLong(), andnextDouble().java.util.concurrent.ThreadLocalRandom– a per-thread random generator, faster in multi-threaded code.java.security.SecureRandom– cryptographically secure, for passwords, tokens, or anything security-sensitive.
For simple games, simulations, or tests, ThreadLocalRandom is usually the best balance of convenience and performance. For security, you must use SecureRandom – never Math.random() or Random for secrets.
How It Works Under the Hood
All non-secure generators in Java are pseudorandom number generators (PRNGs). They use a deterministic algorithm seeded with a 48-bit value. Given the same seed, they produce the same sequence. Random uses a linear congruential generator (LCG) with the formula:
seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)
The returned values are derived from this seed. ThreadLocalRandom uses a similar algorithm but stores its seed in a ThreadLocal, avoiding contention when multiple threads call it simultaneously. SecureRandom uses an entropy source (like /dev/urandom on Linux) to produce unpredictable values, making it suitable for security contexts.
How to Choose the Right Generator
Match the generator to your use case:
- Simple double:
Math.random()– fine for quick prototypes. - General use (single-threaded):
new Random()– thread-safe but slower under contention. - Multi-threaded or high-frequency:
ThreadLocalRandom.current()– fastest in concurrent code. - Security (passwords, tokens, keys):
SecureRandom– never use others.
If you need a specific range, use the bound overloads. For example, to get a random integer between 1 and 100 inclusive, use ThreadLocalRandom.current().nextInt(1, 101). For a double between 5.0 and 10.0, use ThreadLocalRandom.current().nextDouble(5.0, 10.0).
Practical Examples
Here are common patterns with exact code:
// Random integer between 0 and 99 (inclusive of 0, exclusive of 100)int r1 = ThreadLocalRandom.current().nextInt(100);
// Random integer between 1 and 6 (like a die)int r2 = ThreadLocalRandom.current().nextInt(1, 7);
// Random double between 0.0 (inclusive) and 1.0 (exclusive)double r3 = ThreadLocalRandom.current().nextDouble();
// Random booleanboolean r4 = ThreadLocalRandom.current().nextBoolean();
// Random long between 1000 and 2000long r5 = ThreadLocalRandom.current().nextLong(1000, 2001);
For older Java versions (before 1.7), you can use Random:
Random rand = new Random();int r6 = rand.nextInt(100); // 0-99
Note that nextInt(bound) with a bound of 0 throws IllegalArgumentException.
Common Pitfalls and Misconceptions
One frequent mistake is using Math.random() and multiplying to get a range, then forgetting the exclusive upper bound. For example, (int)(Math.random()*100) gives 0 to 99, not 1 to 100. To get 1-100, add 1: (int)(Math.random()*100)+1.
Another misconception: Random is not truly random – it's deterministic. If you create two Random instances with the same seed, they produce identical sequences. This can be useful for testing, but not for security.
Also, avoid creating a new Random object each time you need a number. It's inefficient. Use a single instance or ThreadLocalRandom.
Finally, Random is thread-safe, but if multiple threads share one instance, it can become a bottleneck. ThreadLocalRandom avoids that.
Secure Random Numbers
For passwords, session IDs, or cryptographic keys, use SecureRandom:
SecureRandom secure = new SecureRandom();byte[] bytes = new byte[16];secure.nextBytes(bytes); // fills with random bytes
int secureInt = secure.nextInt(1000); // 0-999
SecureRandom is slower than Random because it gathers entropy from the OS. Never use Math.random() for anything security-related – it's predictable.
Performance Considerations
In single-threaded code, Random and ThreadLocalRandom have similar speed. In multi-threaded code, ThreadLocalRandom is significantly faster because it avoids contention. SecureRandom is the slowest, sometimes 100x slower than Random, so use it only when security is required.
If you need many random numbers in a tight loop, consider generating them in bulk into an array using ints() or doubles() streams (Java 8+):
int[] arr = ThreadLocalRandom.current().ints(1000, 0, 100).toArray();
This is more efficient than calling nextInt() in a loop.
Alternatives and Advanced Usage
Java 17 introduced a new set of interfaces: RandomGenerator, RandomGeneratorFactory, and several new algorithms like Xoshiro256PlusPlus and L64X128MixRandom. You can get a generator with:
RandomGenerator generator = RandomGeneratorFactory.of("L64X128MixRandom").create();int r7 = generator.nextInt(100);
These are faster and have better statistical quality than the old LCG. For most uses, though, ThreadLocalRandom remains the simplest.
If you need to reproduce a sequence (for testing), use new Random(seed) or RandomGeneratorFactory.create(seed).
Frequently Asked Questions
How do I generate a random number between two values?
Use ThreadLocalRandom.current().nextInt(min, max+1) for integers, or nextDouble(min, max) for doubles. The upper bound is exclusive for nextInt, so add 1 to include the max.
Is Math.random() good enough for a dice game?
Yes, for a non-security game, Math.random() works. But ThreadLocalRandom.current().nextInt(1,7) is clearer and avoids casting. The statistical quality is fine for casual use.
Why does my random number repeat often?
That's normal randomness. With a small range, duplicates are expected. For example, rolling a die 6 times often repeats. If you need unique numbers, use a Set or shuffle a list.
Can I use random numbers for passwords?
No. Use SecureRandom for anything security-related. Random and Math.random() are predictable, so an attacker could guess the output.
What is the difference between Random and ThreadLocalRandom?
Random is thread-safe but can be slow under heavy multi-threaded use. ThreadLocalRandom gives each thread its own generator, eliminating contention. Use ThreadLocalRandom in concurrent code.
How do I generate a random UUID in Java?
Use UUID.randomUUID(). It uses SecureRandom internally, so it's safe for unique identifiers. It returns a string like 550e8400-e29b-41d4-a716-446655440000.
Related
- Entry Level Data Entry Clerk: Job, Pay & Skills
- Google Sheets Query Concatenate Columns
- Entry Level Data Entry Companies: Real Jobs & How to Start
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Budget vs Actual Excel Template: Build and Use OneA budget vs actual Excel template compares planned amounts with recorded results by category and period. In Excel…
- Excel Open Corrupted File? Recovery Steps That WorkTo open a corrupted workbook in Excel for Microsoft 365 on Windows, make a copy of the file,…
- Create a Page Template in Word and Save It for ReuseTo create a page template in Word, set up a blank document with the page size, margins, headers,…
- Hanging Indent in Word: Use Ctrl+TTo create a hanging indent in Microsoft Word for Windows, click in the paragraph or select the paragraphs…
- How to Insert a Check Box in Word With a Keyboard ShortcutFor a quick, printable check box in Microsoft Word on Windows, type 2610 and press Alt+X; Word converts…
- Excel Sheet for Employee Schedule: How to Build OneYes, you can build a fully functional employee schedule in Excel using a simple grid layout with dates…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.