Java provides several ways to generate a random integer within a specified range. The right choice depends on your Java version, whether you're in a multithreaded environment, and whether cryptographic quality is required.
Method 1: Math.random()
Math.random() returns a double in the range [0.0, 1.0). To convert it to an integer in a custom range:
public static int randomWithMath(int min, int max) {
return (int) (min + Math.random() * (max - min + 1));
}
System.out.println(randomWithMath(35, 40)); // e.g. 37
System.out.println(randomWithMath(1, 100)); // e.g. 63
The formula min + random * (max - min + 1) scales the [0.0, 1.0) range to [min, max] inclusive. The + 1 ensures the maximum value is reachable (without it, the result is [min, max-1]).
Method 2: java.util.Random
The Random class provides more flexibility and reusability than Math.random():
import java.util.Random;
Random random = new Random();
// nextInt(bound) returns [0, bound) — add min to shift the range
int result = random.nextInt(max - min + 1) + min;
System.out.println(result); // e.g. 38
Using nextInt(bound) is cleaner than the nextDouble() approach because it works directly with integers — no casting needed.
// Full utility method
public static int randomWithRandom(int min, int max) {
Random random = new Random();
return random.nextInt(max - min + 1) + min;
}
System.out.println(randomWithRandom(35, 40)); // e.g. 36
Avoid creating a new Random() inside a tight loop — the same instance is fine to reuse. Creating many instances quickly can produce correlated values on some JVMs.
Method 3: ThreadLocalRandom — Recommended for Most Cases
Java 7 introduced ThreadLocalRandom as the preferred approach for most applications. It's faster than Random in concurrent code because each thread maintains its own generator — no contention:
import java.util.concurrent.ThreadLocalRandom;
// nextInt(min, maxExclusive) — note: upper bound is exclusive
int result = ThreadLocalRandom.current().nextInt(35, 41);
System.out.println(result); // e.g. 39
// General range method
public static int randomThreadLocal(int min, int max) {
return ThreadLocalRandom.current().nextInt(min, max + 1);
}
Note that ThreadLocalRandom.nextInt(min, max) has an exclusive upper bound — unlike Random.nextInt(bound) + min. Pass max + 1 to include the maximum value.
Method 4: SecureRandom — For Security-Sensitive Code
When randomness is used for security purposes (tokens, session IDs, OTPs), use SecureRandom instead. It uses a cryptographically strong algorithm:
import java.security.SecureRandom;
SecureRandom secureRandom = new SecureRandom();
int result = secureRandom.nextInt(max - min + 1) + min;
System.out.println(result);
SecureRandom is slower than the other options — only use it when you actually need cryptographic-quality randomness. For simulations, games, or general use, ThreadLocalRandom is the better choice.
Java 8+: IntStream for Multiple Random Integers
To generate multiple random integers at once, IntStream is convenient:
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
// Generate 10 random integers between 1 and 50
List<Integer> randoms = ThreadLocalRandom.current()
.ints(10, 1, 51) // 10 values, range [1, 51)
.boxed()
.collect(Collectors.toList());
System.out.println(randoms);
// e.g. [23, 7, 45, 12, 33, 5, 49, 18, 31, 2]
Comparison
| Method | Thread-Safe? | Speed | Use When |
|---|---|---|---|
Math.random() | Yes (synchronized) | Slow under contention | Simple one-off use |
java.util.Random | Yes (synchronized) | Slow under contention | Single-threaded code |
ThreadLocalRandom | Yes (no sharing) | Fast | Most applications, multithreaded code |
SecureRandom | Yes | Slow | Security: tokens, OTPs, session IDs |
Summary
For general-purpose random integers in a range, use ThreadLocalRandom.current().nextInt(min, max + 1) — it's the fastest option and safe under concurrent access. Use java.util.Random.nextInt(bound) + min for simple single-threaded code, and SecureRandom only when the randomness is used in a security context such as token generation.
No comments :
Post a Comment
Please leave your message queries or suggetions.
Note: Only a member of this blog may post a comment.