How do I generate a random int
value in a specific range?
I have tried the following, but those do not work:
Attempt 1:
randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
Attempt 2:
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum = minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.
In Java 1.7 or later, the standard way to do this is as follows:
See the relevant JavaDoc. This approach has the advantage of not needing to explicitly initialize a java.util.Random instance, which can be a source of confusion and error if used inappropriately.
However, conversely there is no way to explicitly set the seed so it can be difficult to reproduce results in situations where that is useful such as testing or saving game states or similar. In those situations, the pre-Java 1.7 technique shown below can be used.
Before Java 1.7, the standard way to do this is as follows:
See the relevant JavaDoc. In practice, the java.util.Random class is often preferable to java.lang.Math.random().
In particular, there is no need to reinvent the random integer generation wheel when there is a straightforward API within the standard library to accomplish the task.
It can be done by simply doing the statement:
Below is its source-code
Randomizer.java
It is just clean and simple.
Joshua Bloch. Effective Java. Third Edition.
Starting from Java 8
For fork join pools and parallel streams, use
SplittableRandom
that is usually faster, has a better statistical independence and uniformity properties in comparison withRandom
.To generate a random
int
in the range[0, 1_000]:
To generate a random
int[100]
array of values in the range[0, 1_000]:
To return a Stream of random values:
Use:
The integer
x
is now the random number that has a possible outcome of5-10
.This methods might be convenient to use:
This method will return a random number between the provided min and max value:
and this method will return a random number from the provided min and max value (so the generated number could also be the min or max number):
You can achieve that concisely in Java 8: