**The Price of all “Learn Spring” course packages will increase by ****$40** at **the end of this week:**

**$40**at

**the end of this week:**

Last modified: April 23, 2021

In this tutorial, we'll explore different ways of generating random numbers within a range.

Learn different ways of generating random numbers in Java.

Learn how to generate random numbers in Java - both unbounded as well as within a given interval.

Generate Bounded and Unbounded Random Strings using plain Java and the Apache Commons Lang library.

*Math.random* gives a random *double* value that 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 *[min, max)*:

```
public int getRandomNumber(int min, int max) {
return (int) ((Math.random() * (max - min)) + min);
}
```

Why does that work? Let's look at what happens when *Math.random* returns 0.0, which is the lowest possible output:

`0.0 * (max - min) + min => min`

So, the lowest number we can get is *min*.

Since 1.0 is the exclusive upper bound of *Math.random*, this is what we get:

`1.0 * (max - min) + min => max - min + min => max`

Therefore, the exclusive upper bound of our method's return is *max*.

In the next section, we'll see this same pattern repeated with *Random#nextInt*.

We can also use an instance of *java.util.Random* 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 upper bound *max* is exclusive.

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

In this article, we saw alternative ways of generating random numbers within a range.

Code snippets, as always, can be found over on GitHub.

Follow the Java Category

Follow the Java category to get regular info about the new articles and tutorials we publish here.