Java Language Random Number Generation Pseudo Random Numbers in Specific Range


The method nextInt(int bound) of Random accepts an upper exclusive boundary, i.e. a number that the returned random value must be less than. However, only the nextInt method accepts a bound; nextLong, nextDouble etc. do not.

Random random = new Random();
random.nextInt(1000); // 0 - 999

int number = 10 + random.nextInt(100); // number is in the range of 10 to 109

Starting in Java 1.7, you may also use ThreadLocalRandom (source). This class provides a thread-safe PRNG (pseudo-random number generator). Note that the nextInt method of this class accepts both an upper and lower bound.

import java.util.concurrent.ThreadLocalRandom;

// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
ThreadLocalRandom.current().nextInt(min, max + 1);

Note that the official documentation states that nextInt(int bound) can do weird things when bound is near 230+1 (emphasis added):

The algorithm is slightly tricky. It rejects values that would result in an uneven distribution (due to the fact that 2^31 is not divisible by n). The probability of a value being rejected depends on n. The worst case is n=2^30+1, for which the probability of a reject is 1/2, and the expected number of iterations before the loop terminates is 2.

In other words, specifying a bound will (slightly) decrease the performance of the nextInt method, and this performance decrease will become more pronounced as the bound approaches half the max int value.