This post will discuss how to generate random integers between the specified range in Java.

1. Using Random Class

We can use Random.nextInt() method that returns a pseudorandomly generated int value between 0 (inclusive) and the specified value (exclusive).

 
The following code uses the expression nextInt(max - min + 1) + min to generate a random integer between min and max. It works as nextInt(max - min + 1) generates a random integer between 0 and (max - min), and adding min to it will result in a random integer between min to max.

Download  Run Code

 
In Java 8 and above, we can use the ints() method provided by the Random class, which returns an unlimited stream of pseudorandom int values within the specified range, as shown below:

Download  Run Code

2. Using Math class

We can also use Math.random() that internally uses Random.nextDouble(), and returns a pseudorandom double within the range [0.0, 1.0).

 
The following code uses the following expression to generate a random integer between min and max.

 
It works as Math.random() generates a random double value in the range [0.0, 1.0). When we multiply it by ((max - min) + 1), the lower limit remains 0, but the upper limit becomes (max - min, max - min + 1). Now on casting it with an int, the range becomes [0, max - min], and on adding min, the range becomes [min, max].

Download  Run Code

3. Using ThreadLocalRandom Class

Another option is to use the ThreadLocalRandom class, a subclass of the java.util.Random class for multi threaded environments. This class was introduced in Java 7.

The use of this class is recommended over having shared Random objects in concurrent programs. ThreadLocalRandom offers better performance as a random integer is now generated locally within the same thread.

Download  Run Code

4. Using SecureRandom Class

We can also use the SecureRandom class, a subclass of java.util.Random class, which provides a cryptographically strong random integer generator.

Download  Run Code

5. Using Apache Commons Math

With Apache Commons, we can construct a RandomDataGenerator instance using the supplied RandomGenerator or default random generator as the source of randomness. RandomData can also be used, but it is deprecated now.

Download Code

That’s all about generating random integers between specified ranges in Java.