Pavle Jonoski
By Pavle Jonoski

Generate a random integer within specific range

Generate a random integer within specific range

Generate a random integer within specific range in Java

Very often you need to generate a random number within some range.

Java offers a Random.nextInt(int bound) method, which gives you a random integer between 0 (inclusive) and the bound (exclusive).

We can use this method to generate a random number between a and b:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static int nextRandomIntBetween(int a, int b) {

    if (b <= a) {

        throw new IllegalArgumentException("b must be greater than a");

    }

    int m = b - a;

    Random random = new Random();

    return random.nextInt(m) + a;

}

First, we must ensure that b is greater than a. nextInt(int bound) does not accept negative values.

Then, we calculate the difference b - a. This is the range of our random integers and we can use this

to generate random number between 0 and b - a.

Finally, we add the value of a to the random number, which will make the random number exactly in the range

we wanted.

Here is the full example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.flashreads.examples;



import java.security.SecureRandom;

import java.util.Base64;

import java.util.Random;



public class RandomNumberWithinRangeExample {



    public static void main(String[] args) {

        System.out.println("Here are 10 numbers between 5 (inclusive) and 8 (exclusive):");

        for(int i = 0; i < 10; i++) {

            System.out.println(nextRandomIntBetween(5, 8));

        }



    }





    public static int nextRandomIntBetween(int a, int b) {

        if (b <= a) {

            throw new IllegalArgumentException("b must be greater than a");

        }

        int m = b - a;

        Random random = new Random();

        return random.nextInt(m) + a;

    }

}



Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Here are 10 numbers between 5 (inclusive) and 8 (exclusive):

6

7

5

5

5

6

7

7

6

6