How to Generate Random Numbers in a Range in Java

Random numbers are used in a number of programming applications such as games, computer simulation, cryptography etc. It is also used to generate test data. Usually you want to generate random numbers in a specific range of values. The following example program in Java generates 5 random numbers between 10 and 20 (both inclusive).

import java.util.concurrent.ThreadLocalRandom;

/**
 * Prints random numbers within a range of values inclusive of boundary values.
 * For example, if the range is 10 to 20, this program will print random numbers
 * which will be between 10 and 20 including 10 and 20.
 */
public class RandomInRange {
    
    public static void main(String[] args) {
        // We want numbers to vary from 10 to 20 including 10 and 20.
        int minValueForRange = 10;
        int maxValueForRange = 20;
        
        // create 5 random numbers and then print them
        for(int i=0;i<5;i++) {
            int randomNumber = ThreadLocalRandom.current().nextInt(minValueForRange, maxValueForRange + 1);
            System.out.println(randomNumber);
        }
    }
}

If  you want random floating point values or long values you can use nextDouble() or nextLong() methods of ThreadLocalRandom.

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution on this site within 48 hours! Please email us.


Leave a Reply