Generating random numbers is a common task in Java, used for simulations, games, testing, and security. The simplest approach is to use java.util.Random or Math.random(). For more control (like generating numbers in a specific range or with better performance in multithreaded code), you can use ThreadLocalRandom or SecureRandom. This guide covers all the main ways, with step-by-step examples and best practices.
What You’ll Need
- Java Development Kit (JDK) installed (version 8 or later; the examples work with any modern JDK).
- A text editor or IDE (like IntelliJ, Eclipse, or VS Code).
- Basic knowledge of Java syntax and how to run a Java program (e.g., using
javacandjavacommands).
Step-by-Step
- Choose the right class. For most general purposes, use
java.util.Random. For a single-threaded program,Math.random()is fine. For concurrent applications, useThreadLocalRandom. For security-sensitive data (passwords, tokens), useSecureRandom. - Using
Math.random()(simplest). This returns adoublebetween 0.0 (inclusive) and 1.0 (exclusive). To get an integer between 0 and N-1, multiply and cast:int randomInt = (int)(Math.random() * N);. For a range from min to max (inclusive), use:int randomInRange = min + (int)(Math.random() * ((max - min) + 1));. - Using
java.util.Random(more flexible). Create an instance:Random rand = new Random();. Then call methods:nextInt()(any int),nextInt(bound)(0 to bound-1),nextDouble()(0.0 to 1.0),nextLong(),nextBoolean(), andnextFloat(). - Generate a random integer in a specific range. Use
nextInt(max - min + 1) + min. Example:int dice = rand.nextInt(6) + 1; // 1 to 6. - Generate a random double in a range. Use
min + (max - min) * rand.nextDouble(). Example:double temp = 20.0 + (30.0 - 20.0) * rand.nextDouble(); // 20.0 to 30.0. - Use
ThreadLocalRandomfor multithreaded code. CallThreadLocalRandom.current().nextInt(min, max + 1). This class is thread-safe and often faster than using a sharedRandominstance across threads. - Use
SecureRandomfor security. Create an instance:SecureRandom secureRandom = new SecureRandom();. Then usenextInt(bound)ornextBytes(byte[])to generate cryptographically strong random numbers. - Seed a
Randomfor reproducible results. Pass a long seed to the constructor:new Random(12345L). This is useful for testing or simulations where you want the same sequence each run. - Generate a stream of random numbers (Java 8+). Use
rand.ints(count, min, max)to get anIntStreamof random integers. For example:rand.ints(5, 1, 10).forEach(System.out::println);. - Put it all together. Write a complete program to test. Here’s a full example:
import java.util.Random;
public class RandomExample {
public static void main(String[] args) {
Random rand = new Random();
// Random integer 0-99
int randomInt = rand.nextInt(100);
System.out.println("Random int 0-99: " + randomInt);
// Random double 0.0-1.0
double randomDouble = rand.nextDouble();
System.out.println("Random double: " + randomDouble);
// Random boolean
boolean randomBool = rand.nextBoolean();
System.out.println("Random boolean: " + randomBool);
// Random integer in range 5-10 inclusive
int ranged = 5 + rand.nextInt(6); // 5 to 10
System.out.println("Random 5-10: " + ranged);
}
}
Common Mistakes
- Off-by-one errors. Forgetting that
nextInt(bound)returns 0 to bound-1. To get 1 to 6, usenextInt(6) + 1. - Using
Math.random()for integers without casting correctly. Casting a double to int truncates the decimal, which is fine, but forgetting to multiply by the range gives 0 always. - Creating a new
Randominstance every time. If you create a newRandomin a loop, you might get the same sequence repeatedly (especially if seeded by time). Create one instance and reuse it. - Using
Randomin multithreaded code without synchronization. This can cause unexpected results. UseThreadLocalRandominstead. - Using
Randomfor security-critical data.Randomis predictable; useSecureRandom.
Tips
- For a random integer between min and max (inclusive), always use the formula:
min + rand.nextInt((max - min) + 1). - To generate a random element from an array, use
array[rand.nextInt(array.length)]. - If you need many random numbers, consider using
Randomwith a seed for reproducibility in tests. - For floating-point numbers, remember that
nextDouble()returns a value in [0.0, 1.0). To get a value in [min, max), usemin + (max - min) * rand.nextDouble(). - Use
SecureRandomfor generating passwords, tokens, or any data that must be unpredictable.
Troubleshooting
Problem: Your random numbers are the same every time you run the program.
Solution: If you’re using new Random() without a seed, it should be different each run because it uses the system time. If you’re using a fixed seed, that’s expected. If you’re creating a new Random in a loop, it might get the same seed if the time hasn’t changed; move the instantiation outside the loop.
Problem: You get a NumberFormatException or IllegalArgumentException when using nextInt with a negative bound.
Solution: The bound must be positive. If you need a negative range, use the formula with min and max as described, e.g., min + rand.nextInt(max - min + 1) where min is negative.
Problem: You’re getting values outside the expected range.
Solution: Check your arithmetic. For inclusive ranges, add 1 to the difference. For example, to get 1-6, use rand.nextInt(6) + 1, not rand.nextInt(6) (which gives 0-5).
Problem: ThreadLocalRandom is not available.
Solution: It was introduced in Java 7. If you’re on an older version, upgrade or use Random with synchronization.
Frequently Asked Questions
Q: What is the difference between Math.random() and Random.nextDouble()?
A: Both return a double between 0.0 (inclusive) and 1.0 (exclusive). Math.random() is a static method that internally uses a Random instance, but it’s less flexible because you can’t seed it or get other types. Random.nextDouble() is an instance method, so you can reuse the same random generator and also generate ints, longs, etc.
Q: How do I generate a random number between 1 and 100?
A: Use rand.nextInt(100) + 1 (for Random) or ThreadLocalRandom.current().nextInt(1, 101) (for ThreadLocalRandom).
Q: Can I generate a random char?
A: Yes. For a lowercase letter, use (char)('a' + rand.nextInt(26)). For any ASCII printable character, use (char)(rand.nextInt(95) + 32) (range 32-126).
Q: Is SecureRandom slower than Random?
A: Generally yes, because it uses more computationally intensive algorithms to ensure security. Use it only when you need unpredictability (e.g., security tokens), not for general simulations.
Q: How can I generate a random number without repeating?
A: For a small set, you can shuffle a list of numbers and pick sequentially. For a large set, use a Set to track used numbers and loop until you find an unused one. For a stream, you can use rand.ints().distinct().limit(n).
Q: What does seeding a Random do?
A: Seeding sets the starting point of the pseudorandom number generator. Two Random instances with the same seed will produce the same sequence of numbers. This is useful for testing or debugging.
Related
- Value Dollar Shop Jurong East: Location, Prices & What to Expect
- How to Select All on a Laptop: 5 Fast Ways
- Excel Merge Cells: How to Combine Cells in Excel
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Format by Number Range with Conditional FormattingTo format Excel cells by number range, select the cells and choose Home > Conditional Formatting > Highlight…
- Excel Data Validation Table Column: Dropdowns That ExpandTo make an Excel dropdown use a table column and expand as the table grows, create a workbook-level…
- Excel Dependent Drop-Down Lists With Spaces: Setup GuideYes. In Excel for Microsoft 365 on Windows, you can make a dependent drop-down work when a category…
- COUNTIF TRUE in Google Sheets: Count Boolean ValuesTo count cells whose value is the Boolean TRUE in Google Sheets, use =COUNTIF(A2:A20,TRUE), replacing A2:A20 with your…
- Excel Remove Duplicates by Multiple CriteriaTo remove duplicate records in Excel based on more than one field, select your data, choose Data >…
- How to Unhide Rows in Excel All at Once on WindowsTo unhide every hidden row on an Excel worksheet at once, click the Select All button at the…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.