Java Random Range: Generate Integers in a Range
Learn how to generate random integers in a range in Java using Random, ThreadLocalRandom, SecureRandom, and the RandomGenerator interface.

Generating a random integer within a specific range is a common task in Java, but the right approach depends on the context. In Java, a random range usually means producing an integer between a lower and an upper bound, and several APIs are available. The choice affects thread safety, performance, and whether the result is suitable for security-sensitive operations.
The Core Problem: Generating a Random Integer in a Range
The most frequent requirement is to obtain a random integer between a minimum value (inclusive) and a maximum value (inclusive or exclusive). The classic approach uses java.util.Random and its nextInt(int bound) method, which returns a value from 0 (inclusive) to bound (exclusive). To shift this into a custom range, add an offset. For an inclusive upper bound, add 1 to the range size before calling nextInt.
import java.util.Random;
public class RangeRandom {
public static int randomInclusive(Random random, int min, int max) {
if (max < min) {
throw new IllegalArgumentException("max must be >= min");
}
return random.nextInt((max - min) + 1) + min;
}
}The (max - min) + 1 expression converts the inclusive range into an exclusive bound. For example, min = 5, max = 10 yields nextInt(6), which returns 0–5, and adding 5 gives 5–10. This pattern is straightforward, but (max - min) + 1 can overflow when the range has more than Integer.MAX_VALUE possible values. Use a wider type for such cases, as described in the edge cases section.
Using java.util.Random for a Range
java.util.Random is the classic random number generator. It is thread-safe, but its thread safety relies on an atomic seed update, which can cause contention under high concurrency. For single-threaded code, it is perfectly adequate. If you are on Java 17 or later, the RandomGenerator interface provides a more direct method: nextInt(int origin, int bound), where origin is inclusive and bound is exclusive. This eliminates the manual offset.
import java.util.Random;
public class RangeRandomJava17 {
public static int randomInclusive(Random random, int min, int max) {
// nextInt(origin, bound) is exclusive of bound, so add 1.
return random.nextInt(min, max + 1);
}
}This method is clearer and less error-prone than the manual offset. It still uses int bounds, so it cannot express an inclusive range whose upper bound is Integer.MAX_VALUE, because max + 1 overflows. For that case, widen the range to long as shown in the edge cases section.
ThreadLocalRandom for Concurrent Code
In multi-threaded applications, ThreadLocalRandom is the recommended choice. It provides a separate random generator for each thread, eliminating contention on a shared seed. You access it via ThreadLocalRandom.current(), which returns an instance bound to the calling thread. This class also implements RandomGenerator and offers nextInt(origin, bound) directly.
import java.util.concurrent.ThreadLocalRandom;
public class ThreadRangeRandom {
public static int randomInclusive(int min, int max) {
return ThreadLocalRandom.current().nextInt(min, max + 1);
}
}Because each thread has its own generator, you do not need to pass a Random instance around. This is particularly useful in parallel streams or thread pools where many threads generate random numbers concurrently. The overhead is minimal, and the code is clean. The same max + 1 overflow caveat applies for Integer.MAX_VALUE. Do not use ThreadLocalRandom for cryptographic purposes.
SecureRandom When Security Matters
When the random value is used in security-sensitive contexts—such as generating tokens, passwords, or session IDs—you must use a cryptographically strong generator. SecureRandom provides this by using a secure entropy source and a strong algorithm. It is slower than Random and ThreadLocalRandom, but that is the price of unpredictability. You can use it in the same way for range generation.
import java.security.SecureRandom;
public class SecureRangeRandom {
public static int randomInclusive(SecureRandom random, int min, int max) {
return random.nextInt(min, max + 1);
}
}SecureRandom is thread-safe, but its internal synchronization can become a bottleneck under heavy concurrent load. In such cases, you might use a ThreadLocal<SecureRandom> to give each thread its own instance. Do not use Random or ThreadLocalRandom for anything that requires cryptographic strength.
The RandomGenerator Interface in Java 17+
Java 17 introduced the RandomGenerator interface, which unifies random sources. Random, ThreadLocalRandom, and SecureRandom all implement this interface. It provides standard methods like nextInt(), nextLong(), and the overloaded nextInt(origin, bound). You can also use the RandomGenerator.of(String) factory to obtain a specific implementation by name, such as "L64X128MixRandom" or "Random". This abstraction allows you to write code that works with any random source.
import java.util.random.RandomGenerator;
public class GeneratorRangeRandom {
public static int randomInclusive(RandomGenerator generator, int min, int max) {
return generator.nextInt(min, max + 1);
}
}This is useful for library code that needs to accept a random source from the caller. You can pass a Random, ThreadLocalRandom, or SecureRandom instance, and the method works identically. The interface also includes methods like ints(origin, bound) for generating effectively unlimited streams of random integers.
Handling Edge Cases: Bounds and Inclusive/Exclusive
When working with ranges, consider negative ranges, zero-length ranges, and integer overflow. A zero-length range occurs when min == max; with an inclusive range, the only valid result is that value. Both nextInt(origin, bound) and the offset approach handle this correctly when the bound is strictly greater than the origin. For example, nextInt(5, 6) returns 5, while nextInt(5, 5) throws IllegalArgumentException because the bound must be greater than the origin.
Overflow is trickier. With the classic nextInt(max - min + 1) + min, if max - min + 1 exceeds Integer.MAX_VALUE, the arithmetic overflows and produces a negative bound, causing nextInt to throw. The two-argument nextInt(origin, bound) method is convenient, but its parameters are still int values, so it cannot express an inclusive upper bound of Integer.MAX_VALUE; the exclusive bound would be Integer.MAX_VALUE + 1. For that case, use nextLong with long bounds:
import java.util.random.RandomGenerator;
public class WideRangeRandom {
public static int randomInclusive(RandomGenerator generator, int min, int max) {
if (max < min) {
throw new IllegalArgumentException("max must be >= min");
}
return (int) generator.nextLong(min, (long) max + 1);
}
}The cast back to int is safe because nextLong is called with the original int limits, widened to long, so the returned value is always within the requested int range. This method works for any pair of int bounds, including the full range from Integer.MIN_VALUE through Integer.MAX_VALUE inclusive. For an exclusive upper bound, call nextInt(origin, bound) without adding 1.
Another edge case is when min is negative and max is positive. The offset approach works fine because the arithmetic is done in int space. For example, min = -5, max = 5 yields nextInt(11) - 5, which produces -5 to 5. The nextInt(origin, bound) method also handles negative origins correctly, as long as the bound is greater.
Choosing the Right Random Source
The decision among Random, ThreadLocalRandom, and SecureRandom depends on your concurrency model and security requirements. Use Random for simple, single-threaded code where you need a predictable, reproducible sequence (for example, with a fixed seed for testing). Use ThreadLocalRandom in a multi-threaded environment when you do not need reproducibility or cryptographic strength. It is the default choice for most application code that generates random numbers in parallel. Use SecureRandom only when the output must be unpredictable to an attacker—for example, in security tokens, password salts, or cryptographic keys.
Math.random() is another option, but it is essentially a Random instance behind a static method. It returns a double between 0.0 (inclusive) and 1.0 (exclusive), so you must scale and cast to get an integer. This is less flexible and can be less readable, but it works for quick scripts. For most production code, use one of the dedicated random classes.
The RandomGenerator interface gives you a uniform way to write code that works with any of these sources. If you are building a library, accept a RandomGenerator parameter rather than a concrete class. This keeps your code flexible and future-proof.
Performance and Concurrency Considerations
Performance differences among these generators stem from their underlying algorithms and synchronization strategies. Random uses a linear congruential generator (LCG) and a 48-bit seed. Its thread safety is implemented with a compare-and-set operation on the seed, which can cause cache-line contention when many threads call it simultaneously. In a high-throughput scenario, this contention can degrade performance significantly. ThreadLocalRandom avoids this by giving each thread its own generator instance, so there is no shared state and no contention. The seed is initialized from the thread's own state, and each thread advances its own sequence independently.
SecureRandom is the slowest because it uses a cryptographically strong algorithm, such as a DRBG, and it may block while gathering entropy from the operating system. The exact cost depends on the algorithm and platform, but it is always more expensive than Random or ThreadLocalRandom. Therefore, do not use SecureRandom for non-security purposes, such as game randomness or statistical sampling.
In practice, the performance impact is rarely noticeable unless you generate millions of random numbers per second. For most applications, correctness and thread-safety characteristics matter more than raw speed. Choose ThreadLocalRandom for concurrent code, and you will avoid the most common performance pitfall: shared Random instances causing contention. If you need reproducibility, use Random with a fixed seed and ensure it is not shared across threads. If you need security, use SecureRandom and accept the performance cost.
A final note on stream generation: the RandomGenerator interface provides ints(origin, bound) and longs(origin, bound) methods that return effectively unlimited streams. These are useful for generating a sequence of random values without manually looping. They are lazy, so you can limit them with limit(n) to avoid unbounded generation. This is a clean, idiomatic way to produce a collection of random integers in a range.
Try matching browser tools
All toolsSmall utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Java guides
All Java guidesJava Final Keyword: Usage and Behavior
How Java's final keyword works for variables, methods, and classes, with practical examples and decision guidance for using it.
Java Final Variable: Syntax, Behavior, and Use Cases
Understand what a final variable in Java means, how initialization works, and when to use it for constants, immutability, and clearer code.
Java Duration vs Period: When to Use Each
java duration vs period: Compare Java Duration and Period to handle time-based and date-based calculations correctly. Learn syntax, conversion, and pitfalls.
Instance vs Static Variables in Java: Key Differences
Understand the difference between instance and static variables in Java, including memory, lifecycle, and when to use each.
More in Java
All Java guidesThe guides filed next to this one in Java, in library order.