Java: How to Generate random integers in a range



In this tutorial we will explain how to generate a random intvalue with Java in a specific range, including edges.

What we want is to generate random integers between 5 - 10 , including those numbers.

The class Math has the method random() which returns vlaues between 0.0 and 1.0. The first problem with this method is that it returns a different data type (float). Also the range by defualt is different, but we will see that the range problem is easy to solve.

We also have the Random class which has the method nextInt(int n), this method returns integers betwee 0 and n. In one of our solution we will use the nextInt method.

Solution Java 1.7 or later

import java.util.concurrent.ThreadLocalRandom;

int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);

Since nextInt is exclusive and the right, we add 1 to include our edge case. The values of min is 5 and max is 10.

Solution Before Java 1.7 ,

the standard way to do this is as follows:

import java.util.Random;

public static int generateRandomInteger(int min, int max) {
    if (min >= max) {
        throw new IllegalArgumentException("min argument must be less than max");

    Random generator = new Random(System.currentTimeMillis()); // see comments!
    int randomNum = rand.nextInt((max - min) + 1) + min;

    return rand

Our static function will generate a random integer between min and max.

We are using current time in milliseconds as a seed for the random number generator, this is very insecure.
Remeber that the seed should not be easy to guess, since an attacker coudl guestt the seed and predict your random numbers.

We recommend to search more about random number and seeds if you need a secure random number generator.

# Solution: Using Math class

Min + (int)(Math.random() * ((Max - Min) + 1))

To get the values between your range you need to you need to multiply by the magnitude of the range, which in this case is ( Max - Min ). Since the random is exclusive on right limit we need to add 1. Now that random generates from 0.0 we need to add Min to the whole number. To solve the data type problem we cast the value to int.

Example of usage

As an example we will generate 10 random numbers between 100 and 1000

for (int i = 0; i < 10; i++) {
    System.out.println(generateRandomInteger(100, 1000));