Java Random Number Generator

Learn how to generate random numbers in Java with interactive code examples. Explore Random.nextInt(), SecureRandom, ThreadLocalRandom, and Math.random() with detailed explanations.

Java Code Editor

Java Code
import java.util.Random;

public class RandomExample {
    public static void main(String[] args) {
        Random rand = new Random();
        int min = 1;
        int max = 100;
        int quantity = 5;

        System.out.println("Random numbers between " + min + " and " + max + ":");
        for (int i = 0; i < quantity; i++) {
            int num = rand.nextInt(max - min + 1) + min;
            System.out.print(num + " ");
        }
    }
}
Output

This is a browser preview, not execution of Java or C++. Preview values are not suitable for cryptographic use.

Preview example

Basic Random with java.util.Random

Use Random.nextInt() to generate random integers in a specific range. This is the most common method for general-purpose random number generation in Java.

Need a Quick Random Number?

Try our online random number generator for instant results without writing any code.

Open Random Number Generator

Understanding Java Random Number Generation

Java provides multiple ways to generate random numbers, each optimized for different use cases. java.util.Random uses a Linear Congruential Generator (LCG) algorithm, SecureRandom provides cryptographically strong random numbers, ThreadLocalRandom offers thread-safe generation for concurrent applications, and Math.random() provides a simple way to generate random doubles.

java.util.Random

java.util.Random provides fast pseudo-random number generation suitable for simulations, games, and general programming tasks. Thread-safe for basic use.

SecureRandom

java.security.SecureRandom uses platform-specific algorithms (SHA1PRNG, NativePRNG) to generate cryptographically secure random numbers for security applications.

ThreadLocalRandom

ThreadLocalRandom provides efficient thread-safe random number generation specifically designed for multi-threaded applications, avoiding contention and synchronization overhead.

Math.random()

Math.random() is a simple method that returns a double value between 0.0 and 1.0. Convenient for quick calculations but less flexible than other options.

Common Use Cases

Gaming & Simulations

Generate random dice rolls, card draws, enemy spawns, and game events using Random.nextInt() or ThreadLocalRandom in game loops.

Security & Cryptography

Create secure passwords, API keys, session tokens, and encryption salts using SecureRandom for cryptographic strength randomness.

Concurrent Applications

Use ThreadLocalRandom in parallel streams and multi-threaded applications to avoid contention and improve performance.

Software Testing

Create randomized test data, fuzz testing inputs, and edge cases to ensure robust code coverage and bug detection in Java applications.

How Java Random Number Generation Works

Java's java.util.Random class uses a Linear Congruential Generator (LCG) algorithm with a 48-bit seed. It provides a simple way to generate pseudo-random numbers and is synchronized for thread safety.

The SecureRandom class provides cryptographically strong random numbers by using platform-specific implementations. On most systems, it uses the operating system's entropy source or hardware random number generators.

ThreadLocalRandom, introduced in Java 7, is designed for multi-threaded applications. It uses a random number generator that is isolated to the current thread, avoiding synchronization overhead and contention.

Practical tips

🎯

Choose the Right API

Use Random for simple cases, SecureRandom for security, ThreadLocalRandom for concurrent apps, and Math.random() only for quick prototypes. Each has specific use cases.

🔒

Always Use SecureRandom for Security

Never use Random or Math.random() for passwords, tokens, or cryptographic operations. Always use SecureRandom to ensure strong randomness and avoid predictable patterns.

⚡

Optimize for Concurrent Access

In multi-threaded applications, ThreadLocalRandom is significantly faster than synchronizing Random objects. Use it in parallel streams and concurrent collections.

Technical Specifications

Algorithms

  • Linear Congruential Generator (Random class)
  • SHA1PRNG or NativePRNG (SecureRandom)
  • ThreadLocalRandom (Java 7+, based on Random)
  • Pseudo-random double (Math.random())

Performance Characteristics

  • Math.random(): Fastest for simple doubles
  • ThreadLocalRandom: Best for concurrent access
  • Random: Good general-purpose, synchronized overhead
  • SecureRandom: Slower due to entropy gathering

Frequently Asked Questions

Which Java APIs are covered?

java.util.Random, SecureRandom, ThreadLocalRandom and Math.random(), each with a focused example.

Can I tailor the examples?

Yes. Set minimum, maximum and quantity in the parameters panel and run to see results instantly.

Which one should I use for security?

SecureRandom. The other APIs are predictable and must not back tokens, keys or passwords.

What about multithreaded code?

ThreadLocalRandom avoids contention between threads and is the usual pick inside parallel streams and thread pools.

How do I generate a random number between two values in Java?

Call nextInt(bound) for values from 0 up to bound-1, so nextInt(50) yields 0 through 49. For a custom range, add an offset: nextInt(10) + 5 produces 5 through 14. Since Java 17, nextInt(origin, bound) does this in one call, with origin inclusive and bound exclusive.

Can Math.random() return 1?

No. Math.random() returns a double from 0.0 inclusive up to but never including 1.0, so 0.0 or 0.9999 can appear but 1.0 never does. Internally it delegates to a single java.util.Random instance, so calling Random methods directly is clearer for modern code.

Why do I get the same random numbers every time I run my program?

A Random created with a fixed seed, such as new Random(42), always reproduces the identical sequence. Drop the seed argument and it seeds automatically from a unique value combined with System.nanoTime(). Fixed seeds are handy for reproducible tests and debugging but should stay out of production code.

How do I pick a random element from an array or list?

Generate an index and read that position: list.get(random.nextInt(list.size())) for lists or array[random.nextInt(array.length)] for arrays, since nextInt(n) spans 0 through n-1. Alternatively, Collections.shuffle() randomizes the entire list order in one pass, so no element repeats within a single shuffle.

Does the generator remember my previous inputs and settings?

Yes. Everything you type and every option you choose is kept only in your own browser's local storage on this device. Reload the page or come back later and your last text, quantities, and format choices are restored instantly, with no account and no upload — nothing is stored on any server, and a different device or browser keeps its own separate memory. Clearing a field removes it from memory immediately, and emptying every field makes the tool forget everything. Uploaded files are never saved; only plain settings such as sizes, formats, styles, and separators are remembered on your device, and you can change them at any time.

References & Resources

Free Online Tools for the United States US

Do Generator for the United States brings you free online tools tuned for American workflows. Generate secure random numbers, scannable QR codes, retail barcodes (UPC-A, EAN-13), and strong passwords with US-friendly formatting, English (US) spelling, and mobile-first layouts that work across all 50 states.

Programming tools and code generators for developers. Learn how to generate random numbers, strings, and data in various programming languages