How to get random number in a range in Java

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 the 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.

Leave a Reply