Java Random Number Generator
Random numbers in Java: a random integer in any range, floats, picking and shuffling, and secure random values - with ready-to-paste code
How to generate a random number in Java: ThreadLocalRandom or java.util.Random for everyday use, SecureRandom for anything security-related. Choose a range above for a ready-to-paste class.
Random Int Between Min and Max
Upper bounds are exclusive in Java's random APIs, so add 1 to include the maximum.
import java.util.concurrent.ThreadLocalRandom;
int n = ThreadLocalRandom.current().nextInt(1, 11); // 1..10
import java.util.Random;
Random random = new Random();
int m = random.nextInt(10) + 1; // 1..10
Random Double
nextDouble() returns a value in [0.0, 1.0).
double d = ThreadLocalRandom.current().nextDouble(); // 0.0 <= d < 1.0
double e = ThreadLocalRandom.current().nextDouble(1.5, 4.5); // 1.5 <= e < 4.5
Random Element and Shuffle
Pick by index, or shuffle a list with Collections.shuffle.
List<String> items = new ArrayList<>(List.of("red", "green", "blue"));
String pick = items.get(ThreadLocalRandom.current().nextInt(items.size()));
Collections.shuffle(items); // in place
Collections.shuffle(items, new SecureRandom()); // secure shuffle
Secure Random Numbers with SecureRandom
java.util.Random is predictable. Use SecureRandom for passwords, tokens and draws - create it once and reuse it.
import java.security.SecureRandom;
SecureRandom secure = new SecureRandom();
int n = secure.nextInt(10) + 1; // 1..10
byte[] token = new byte[16];
secure.nextBytes(token);
Common Mistakes
Math.abs(random.nextInt()) % n can return a negative number (the absolute value of Integer.MIN_VALUE is still negative) and is biased - use nextInt(n). Creating a new Random on every call wastes time; reuse one instance or use ThreadLocalRandom.
Frequently Asked Questions
How do I generate a random number between 1 and 10 in Java? ▶
How do I import Random in Java? ▶
What is the difference between Random and SecureRandom? ▶
Is nextInt(bound) inclusive? ▶
[ HOW TO CITE THIS PAGE ]
Generate-Random.org. (2026). Java Random Number Generator. Retrieved from https://generate-random.org/random-number-java
Java Random Number Generator - Generate-Random.org (https://generate-random.org/random-number-java)