How to Get a Random Number in Java

How-to basics · Updated November 23, 2026

Generating a random number 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 integers or more control, use the Random class from java.util. This guide covers both methods, plus the modern ThreadLocalRandom and the cryptographically secure SecureRandom.

What You’ll Need

  • Java Development Kit (JDK) installed (version 8 or later works for all examples).
  • A text editor or IDE (like IntelliJ, Eclipse, or VS Code).
  • Basic knowledge of Java syntax and how to run a program.

Step-by-Step

  1. Use Math.random() for a quick double.
    The simplest method: double r = Math.random(); returns a value from 0.0 up to but not including 1.0. To get a number in a range, multiply and add. For example, a random double between 1.0 and 10.0: double r = 1.0 + (Math.random() * 9.0);.
  2. Get a random integer with Math.random().
    Cast to int after scaling. For a random integer from 1 to 10: int r = (int)(Math.random() * 10) + 1;. The multiplication gives 0.0–9.999…, casting truncates to 0–9, then adding 1 shifts to 1–10.
  3. Use the Random class for more options.
    Import java.util.Random, then create an instance: Random rand = new Random();. Call methods like nextInt(), nextDouble(), nextBoolean(), or nextLong(). For a random integer in a range (0 to bound-1): int r = rand.nextInt(10); gives 0–9. For 1–10, use rand.nextInt(10) + 1.
  4. Generate a random integer in a specific range (min to max inclusive).
    Use rand.nextInt((max - min) + 1) + min. Example: random between 5 and 15: int r = rand.nextInt(11) + 5; because max-min+1 = 11, and adding 5 shifts the range.
  5. Use ThreadLocalRandom for concurrency or convenience.
    In Java 7+, you can call ThreadLocalRandom.current().nextInt(min, max+1) to get a random integer directly in a range. For a double: ThreadLocalRandom.current().nextDouble(min, max). This is thread-safe and often faster than Random in multithreaded code.
  6. Use SecureRandom for security-sensitive randomness.
    For passwords, tokens, or cryptographic keys, use SecureRandom from java.security. Instantiate with SecureRandom secureRand = new SecureRandom(); and call nextInt(bound) or nextBytes(). This provides a cryptographically strong random number generator.
  7. Put it all together in a complete example.
    Write a simple program to test:

    import java.util.Random;
    
    public class RandomExample {
        public static void main(String[] args) {
            // Math.random()
            double d = Math.random();
            System.out.println("Double: " + d);
    
            // Random class
            Random rand = new Random();
            int r = rand.nextInt(100); // 0-99
            System.out.println("Integer: " + r);
    
            // Range 1-100
            int ranged = rand.nextInt(100) + 1;
            System.out.println("1-100: " + ranged);
        }
    }

    Compile with javac RandomExample.java and run with java RandomExample.

  8. Seed the Random class if you need reproducible results.
    Pass a long seed to the constructor: new Random(42L). The same seed produces the same sequence, useful for testing. Math.random() cannot be seeded directly.

Common Mistakes

  • Forgetting to import java.util.Random. You’ll get a compilation error. Add the import at the top of your file.
  • Using nextInt(bound) with a negative bound. Throws IllegalArgumentException. Always use positive bounds.
  • Off-by-one errors in ranges. Remember nextInt(n) returns 0 to n-1. If you want 1–10, use nextInt(10)+1, not nextInt(11) (that gives 0–10).
  • Using Math.random() for integers without casting correctly. (int)Math.random()*10 always yields 0 because the cast happens first. Use parentheses: (int)(Math.random()*10).
  • Using Random in multi-threaded code without synchronization. Random is not thread-safe; use ThreadLocalRandom instead.
  • Using Math.random() for security. It’s not cryptographically secure. Use SecureRandom.

Tips

  • For a random boolean, use rand.nextBoolean() or ThreadLocalRandom.current().nextBoolean().
  • To get a random element from an array, use array[rand.nextInt(array.length)].
  • For a random float, use rand.nextFloat() (returns 0.0–1.0).
  • If you need many random numbers, create a single Random instance and reuse it; creating a new one each time is slower.
  • Use Stream methods like rand.ints(5, 1, 100) to generate a stream of 5 random integers between 1 and 99 (inclusive of 1, exclusive of 100).
  • For reproducible tests, seed your Random and log the seed.

Troubleshooting

  • Compilation error: “cannot find symbol” for Random. Add import java.util.Random; at the top of your file.
  • Program throws IllegalArgumentException when calling nextInt(0). The bound must be positive. Use nextInt(1) to get 0, or check your logic.
  • Your random numbers are always the same. If you create a new Random with the same seed each time, you’ll get the same sequence. Remove the seed or use a different seed (e.g., System.currentTimeMillis()).
  • Random numbers are not evenly distributed. Math.random() and Random are uniformly distributed, but if you’re using modulo, bias can occur. For critical applications, use nextInt(bound) which handles distribution properly.
  • Getting a negative number from nextInt(). The no-arg nextInt() returns any int, including negative. Use nextInt(bound) to restrict to non-negative.

Frequently Asked Questions

  1. 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. It internally uses a Random object. The Random class offers more methods (like nextInt, nextLong) and allows seeding for reproducible sequences.
  2. How do I get a random number between 1 and 100 inclusive?
    Use Random rand = new Random(); int r = rand.nextInt(100) + 1; or ThreadLocalRandom.current().nextInt(1, 101) (the upper bound is exclusive).
  3. Can I get a random decimal number between two values?
    Yes. For a double between min and max: min + (Math.random() * (max - min)). For example, between 5.5 and 10.5: 5.5 + (Math.random() * 5.0).
  4. Is Random thread-safe?
    No, Random is not thread-safe. If multiple threads share a Random instance, use synchronization or, better, ThreadLocalRandom which is designed for concurrent use.
  5. How do I generate a random password or token?
    Use SecureRandom to generate bytes and encode them (e.g., Base64). For example: byte[] bytes = new byte[16]; new SecureRandom().nextBytes(bytes); then convert to a string.
  6. What is the difference between Random and SecureRandom?
    Random uses a linear congruential formula, which is fast but predictable. SecureRandom uses a cryptographically strong algorithm (like SHA1PRNG) that is unpredictable and suitable for security-sensitive tasks.

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.