1. Overview
In this tutorial, we'll explore different ways of generating random numbers within a range.
2. Generating Random Numbers in a Range
2.1. Math.random
The Math.random gives a random double value which is greater than or equal to 0.0 and less than 1.0.
Let's use the Math.random method to generate a random number in a given range:
public int getRandomNumber(int min, int max) { return (int) ((Math.random() * (max - min)) + min); }
Why does that work? Well, let's look at what happens when Math.random returns 0.0, it's lowest possible output:
0.0 * (max - min) + min => min
So, the lowest number we can get is min.
If Math.random returns 1.0, it's highest possible output, then we get:
1.0 * (max - min) + min => max - min + min => max
So, the highest number we can get is max.
Let's see this same pattern repeated with Random#nextInt in the next section.
2.2. java.util.Random.nextInt
An instance of java.util.Random can be also used to do the same.
Let's make use of the java.util.Random.nextInt method to get a random number:
public int getRandomNumberUsingNextInt(int min, int max) { Random random = new Random(); return random.nextInt(max - min) + min; }
The min parameter (the origin) is inclusive, whereas the max, the bound, is exclusive
2.3. java.util.Random.ints
The java.util.Random.ints method returns an IntStream of random integers.
So, we can utilize the java.util.Random.ints method and return a random number:
public int getRandomNumberUsingInts(int min, int max) { Random random = new Random(); return random.ints(min, max) .findFirst() .getAsInt(); }
Here as well, the specified origin min is inclusive and max is exclusive.
3. Conclusion
In this article, we saw alternative ways of generating random numbers within a range.
Code snippets, as always, can be found over on GitHub.