Generate random integers in a specific range

Generate random integers in a specific range using Java

Java 8

To generate a random int in the from 1 inclusive to 100 inclusive using Java 8:

import java.util.SplittableRandom;
int randNum = new SplittableRandom().nextInt(0, 101);
Note
SplittableRandom().nextInt(origin, bound): The bound of SplittableRandom().nextInt is exclusive, so you have to add 1 to the top to make sure the top value is inclusive.

To generate 100 random int numbers as array which has values in a specific range such as [1, 100]

int[] randInts = new SplittableRandom().ints(100, 0, 101).toArray();

Java 1.7 or later

import java.util.concurrent.ThreadLocalRandom;

// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randNum = ThreadLocalRandom.current().nextInt(min, max + 1);

Tthe advantage of this way is that, this way doesn’t need to explicitly initialize a java.util.Random instance.

Before Java 1.7

The standar approach to generate random integers within a specific range is using java.util.Random

import java.util.Random;

public class Example {

    private static final Random rand = new Random();

    public static void main(final String... args) {
        System.out.println(randInt(1, 20));
        System.out.println(randInt(1, 20));
        System.out.println(randInt(1, 20));
        System.out.println(randInt(1, 20));
    }

    private static int randInt(final int min, final int max) {
        return rand.nextInt(max - min + 1) + min;
    }
}

// Output maybe:
// 10
// 17
// 11
// 16
//
Last modified October 4, 2020