How to Use Random Numbers in Java

How-to basics · Updated November 24, 2026

Generating random numbers in Java is a common task for games, simulations, testing, and security. The simplest way is to use Math.random(), which returns a double between 0.0 (inclusive) and 1.0 (exclusive). For more control—like generating integers within a range or cryptographically secure numbers—use the Random class or SecureRandom. This guide walks you through each method with code examples.

What You’ll Need

  • Java Development Kit (JDK) 8 or later installed (most examples work on older versions too).
  • A text editor or an IDE like IntelliJ IDEA, Eclipse, or VS Code.
  • Basic familiarity with Java syntax (classes, methods, variables).

Step-by-Step

Method 1: Using Math.random()

  1. Create a new Java class (e.g., RandomDemo.java) with a main method.
  2. Call Math.random() to get a random double between 0.0 and 1.0:
    double rand = Math.random();
    System.out.println(rand);
  3. Generate an integer in a range (e.g., 1 to 10):
    int min = 1;
    int max = 10;
    int randomInt = (int)(Math.random() * (max - min + 1)) + min;
    System.out.println(randomInt);

    Explanation: Math.random() gives 0.0 to 0.999…, multiply by 10 gives 0.0 to 9.999…, cast to int truncates to 0–9, then add 1 to get 1–10.

Method 2: Using the Random Class

  1. Import the class at the top of your file:
    import java.util.Random;
  2. Create an instance of Random:
    Random random = new Random();
  3. Generate different types of random values:
    • random.nextInt() – any integer (including negative).
    • random.nextInt(bound) – integer from 0 (inclusive) to bound (exclusive).
    • random.nextDouble() – double between 0.0 and 1.0.
    • random.nextBoolean() – true or false.

    Example:

    int dice = random.nextInt(6) + 1; // 1 to 6
    System.out.println(dice);
  4. Generate a random integer in a custom range (e.g., 5 to 15):
    int min = 5;
    int max = 15;
    int result = random.nextInt(max - min + 1) + min;
    System.out.println(result);

Method 3: Using SecureRandom for Security-Sensitive Applications

  1. Import the class:
    import java.security.SecureRandom;
  2. Create an instance:
    SecureRandom secureRandom = new SecureRandom();
  3. Use it similarly to Random:
    int token = secureRandom.nextInt(1000000); // 0 to 999999
    System.out.println(token);

    Use SecureRandom for passwords, tokens, and anything security-related because it uses a cryptographically strong algorithm.

Method 4: Using ThreadLocalRandom (for concurrent code)

  1. Import the class:
    import java.util.concurrent.ThreadLocalRandom;
  2. Generate a random integer in a range directly:
    int randomNum = ThreadLocalRandom.current().nextInt(1, 11); // 1 to 10
    System.out.println(randomNum);

    This is faster in multi-threaded environments and is the recommended way for simple random numbers in Java 7+.

Common Mistakes

  • Off-by-one errors: Forgetting to add 1 when using nextInt(bound) or Math.random() to get a range that includes the upper bound.
  • Using Random for security: Random is predictable; use SecureRandom for passwords or tokens.
  • Creating a new Random instance every call: This can produce identical sequences if created in rapid succession. Create one instance and reuse it.
  • Ignoring the exclusive upper bound: nextInt(10) returns 0–9, not 1–10.

Tips

  • Seed a Random instance for reproducible results (e.g., in tests): new Random(42L).
  • Use ThreadLocalRandom for most cases—it’s cleaner and avoids concurrency issues.
  • Generate a random char from a string: String chars = "ABC123"; char c = chars.charAt(random.nextInt(chars.length()));
  • Shuffle a list using Collections.shuffle(list, random).
  • For doubles in a range: min + (max - min) * random.nextDouble().

Troubleshooting

  • Getting the same numbers every run: If you use new Random() without a seed, it should differ; but if you create a new instance every millisecond, it might repeat. Use one instance or ThreadLocalRandom.
  • Compilation errors about Random not found: Make sure you imported java.util.Random.
  • Numbers out of expected range: Double-check your formula. For nextInt(bound), the result is 0 to bound-1. Add an offset correctly.
  • Security exception when using SecureRandom: On some systems, the default algorithm may be slow or blocked. You can specify an algorithm: SecureRandom.getInstanceStrong() or use new SecureRandom() which usually works.
  • Random numbers not truly random: Random uses a linear congruential generator—fine for most purposes, but not for cryptography. Switch to SecureRandom.

Frequently Asked Questions

What is the difference between Math.random() and Random?

Math.random() is a static method that returns a double between 0.0 and 1.0. The Random class provides methods for various types (int, double, boolean) and allows seeding for reproducibility. Use Random for more flexibility.

How do I generate a random number between 1 and 100?

Using Random: random.nextInt(100) + 1. Using Math.random(): (int)(Math.random() * 100) + 1.

Can I generate a random number without importing anything?

Yes, Math.random() is part of java.lang and requires no import. For other classes, you need imports.

Is Random thread-safe?

No, Random is not thread-safe. Use ThreadLocalRandom for concurrent use or synchronize access.

How do I generate a random string?

Combine random integers with a character set. For example, generate a random index into a string of allowed characters and repeat for the desired length.

Why does SecureRandom sometimes throw an exception?

It may fail if the system’s entropy source is unavailable. You can handle it by falling back to new SecureRandom() or specifying a provider.

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.