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

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

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 optimised 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.

⚡

Optimise 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.

References & Resources

Free Online Tools for India IN

Do Generator India brings you free online tools optimized for Indian users. From random number generation to QR codes, barcodes, and AI prompts, our tools support Indian English conventions, six-digit PIN code patterns, mobile-first workflows, and content needs across India.