How to Generate Random Numbers in Java
Last updated: July 9, 2026
Java offers several ways to generate random numbers, each suited to a different situation. This guide covers all four. Prefer no code? Use our Random Number Generator.
Math.random()
The simplest option returns a double between 0.0 (inclusive) and 1.0 (exclusive):
double d = Math.random();
For a whole number from 1 to 100:
int n = (int)(Math.random() * 100) + 1;
java.util.Random
More flexible and reusable. Create one instance and call its methods:
Random rand = new Random();
int n = rand.nextInt(100) + 1; // 1 to 100
nextInt(bound) returns 0 to bound-1, nextDouble() returns a float, and nextBoolean() returns true or false.
ThreadLocalRandom (for concurrency)
In multi-threaded code, ThreadLocalRandom is faster and avoids contention:
int n = ThreadLocalRandom.current().nextInt(1, 101); // 1 to 100
SecureRandom (for security)
For passwords, tokens and cryptographic keys, always use SecureRandom, which is cryptographically strong:
SecureRandom secure = new SecureRandom();
int n = secure.nextInt(100);
Never use Math.random() or a plain Random for security-sensitive values.
Which should you use?
- Quick one-off —
Math.random() - General purpose —
java.util.Random - Multi-threaded —
ThreadLocalRandom - Security —
SecureRandom
For a fast, no-setup result you can copy anywhere, try the Random Number Generator or the Password Generator on Toolssy.