Generate random integers between specified ranges in Java
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.util.Random; class Main { /** * Generates a pseudorandom integer in the range [min, max] * @param `min` The starting value of the range (inclusive) * @param `max` The ending value of the range (inclusive) */ public static int rand(int min, int max) { if (min > max || (max - min + 1 > Integer.MAX_VALUE)) { throw new IllegalArgumentException("Invalid range"); } return new Random().nextInt(max - min + 1) + min; } public static void main(String[] args) { int min = 1, max = 10; for (int i = 0; i < 10; i++) { System.out.println(rand(min, max)); } } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import java.util.Random; class Main { /** * Generates a pseudorandom integer in the range [min, max] * @param `min` The starting value of the range (inclusive) * @param `max` The ending value of the range (inclusive) */ public static int rand(int min, int max) { if (min > max) { throw new IllegalArgumentException("Invalid range"); } Random rand = new Random(); return rand.ints(min, (max + 1)) // IntStream .findFirst() // OptionalInt .getAsInt(); // int } public static void main(String[] args) { int min = 1, max = 10; for (int i = 0; i < 10; i++) { System.out.println(rand(min, max)); } } } |
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.
|
1 |
(int)(Math.random() * ((max - min) + 1)) + min |
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].
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
class Main { /** * Generates a pseudorandom integer in the range [min, max] * @param `min` The starting value of the range (inclusive) * @param `max` The ending value of the range (inclusive) */ public static int rand(int min, int max) { if (min > max) { throw new IllegalArgumentException("Invalid range"); } double rand = Math.random(); return (int)(rand * ((max - min) + 1)) + min; } public static void main(String[] args) { int min = 1, max = 10; for (int i = 0; i < 10; i++) { System.out.println(rand(min, max)); } } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import java.util.concurrent.ThreadLocalRandom; class Main { /** * Generates a pseudorandom integer in the range [min, max] * @param `min` The starting value of the range (inclusive) * @param `max` The ending value of the range (inclusive) */ public static int rand(int min, int max) { if (min > max) { throw new IllegalArgumentException("Invalid range"); } return ThreadLocalRandom.current() .nextInt(min, max + 1); } public static void main(String[] args) { int min = 1, max = 10; for (int i = 0; i < 10; i++) { System.out.println(rand(min, max)); } } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import java.security.SecureRandom; class Main { /** * Generates a pseudorandom integer in the range [min, max] * @param `min` The starting value of the range (inclusive) * @param `max` The ending value of the range (inclusive) */ public static int rand(int min, int max) { if (min > max || (max - min + 1 > Integer.MAX_VALUE)) { throw new IllegalArgumentException("Invalid range"); } // obtain a `SecureRandom` instance and seed the instance with seed bytes // using the generateSeed method SecureRandom random = new SecureRandom(); random.setSeed(random.generateSeed(20)); // nextInt() is inherited from class java.util.Random return random.nextInt((max - min) + 1) + min; } public static void main(String[] args) { int min = 1, max = 10; for (int i = 0; i < 10; i++) { System.out.println(rand(min, max)); } } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import org.apache.commons.math3.random.JDKRandomGenerator; import org.apache.commons.math3.random.RandomDataGenerator; class Main { /** * Generates a pseudorandom integer in the range [min, max] * @param `min` The starting value of the range (inclusive) * @param `max` The ending value of the range (inclusive) */ public static int rand(int min, int max) { if (min > max) { throw new IllegalArgumentException("Invalid range"); } return new RandomDataGenerator(new JDKRandomGenerator()) .nextInt(min, max); } public static void main(String[] args) { int min = 1, max = 10; for (int i = 0; i < 10; i++) { System.out.println(rand(min, max)); } } } |
That’s all about generating random integers between specified ranges in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)