Java generate random number in a range

Let’s see how we can randomly generate numbers from the range in java

1. java.util.Random.nextInt

new Random().nextInt((max-min+1))+min

2. Math.random

(int)(Math.random() * ((max - min) + 1))+min

3. ThreadLocalRandom.current().nextInt()

ThreadLocalRandom.current().nextInt(min, max + 1)+min

4. java.util.Random.ints

new Random().ints(min, (max + 1)).findFirst().getAsInt()

In the next section we will explore with examples

[addToAppearHere]

1. java.util.Random.nextInt
The formula for generating random number from range (upper/lower bounds inclusive) is

new Random().nextInt((max-min+1))+min;
new Random().nextInt(10) // [0,10) upper bound excluded
new Random().nextInt(10+1) // [0,10] upper bound included

if we want generate random number from range we have the following:

new Random().nextInt((10-5))+5; // [5,10), upper bound excluded

new Random().nextInt((10-5)) will generate numbers from [0,5) and the by adding 5 will make an offset so that number will be in [5,10) range
if we want to have upper bound inclusive just need to do the following

new Random().nextInt((10-5+1))+5; // [5,10], upper bound included

2. Math.random

(int)(Math.random() * ((max - min) + 1))+min
Math.random() // will generate random double number in [0,1) range, 1 is excluded
Math.random() * (10-5) // will generate value in [0,10-5), upper bound excluded

To include upper bound

Math.random() * (10-5)+1 // generated number in [0,5] range

To make an offset with 5 just add the value at the end

(int)(Math.random() * ((10 - 5) + 1))+5 // generated number in [5,10] range

3. ThreadLocalRandom.current().nextInt()

ThreadLocalRandom.current().nextInt(min, max + 1)+min

We can use the same way as Random.nextInt(), the difference is that in concurrent applications better to use ThreadLocalRandom to avoid possible contention issues.

4. java.util.Random.ints

new Random().ints(min, (max + 1)).findFirst().getAsInt();
new Random().ints(5, (10 + 1)).findFirst().getAsInt(); // will generate int in [5,10] range, 10 included