How to Randomly Generate Numbers in Java

How-to basics · Updated November 22, 2026

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 javac and java commands).

Step-by-Step

  1. Choose the right class. For most general purposes, use java.util.Random. For a single-threaded program, Math.random() is fine. For concurrent applications, use ThreadLocalRandom. For security-sensitive data (passwords, tokens), use SecureRandom.
  2. Using Math.random() (simplest). This returns a double between 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));.
  3. 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(), and nextFloat().
  4. Generate a random integer in a specific range. Use nextInt(max - min + 1) + min. Example: int dice = rand.nextInt(6) + 1; // 1 to 6.
  5. 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.
  6. Use ThreadLocalRandom for multithreaded code. Call ThreadLocalRandom.current().nextInt(min, max + 1). This class is thread-safe and often faster than using a shared Random instance across threads.
  7. Use SecureRandom for security. Create an instance: SecureRandom secureRandom = new SecureRandom();. Then use nextInt(bound) or nextBytes(byte[]) to generate cryptographically strong random numbers.
  8. Seed a Random for 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.
  9. Generate a stream of random numbers (Java 8+). Use rand.ints(count, min, max) to get an IntStream of random integers. For example: rand.ints(5, 1, 10).forEach(System.out::println);.
  10. 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, use nextInt(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 Random instance every time. If you create a new Random in a loop, you might get the same sequence repeatedly (especially if seeded by time). Create one instance and reuse it.
  • Using Random in multithreaded code without synchronization. This can cause unexpected results. Use ThreadLocalRandom instead.
  • Using Random for security-critical data. Random is predictable; use SecureRandom.

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 Random with 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), use min + (max - min) * rand.nextDouble().
  • Use SecureRandom for 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

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.