Java 7+

In Java 1.7 or later, the standard way to do this (generate a basic non-cryptographically secure random integer in the range [min, max]) is as follows:

import java.util.concurrent.ThreadLocalRandom;

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

See the relevant JavaDoc. This approach has the advantage of not needing to explicitly initialize a java.util.Random instance, which can be a source of confusion and error if used inappropriately.

However, conversely with ThreadLocalRandom there is no way to explicitly set the seed so it can be difficult to reproduce results in situations where that is useful such as testing or saving game states or similar.

Java 17+

As of Java 17, the psuedorandom number generating classes in the standard library implement the RandomGenerator interface. See the linked JavaDoc for more information. For example, if a cryptographically strong random number generator is desired, the SecureRandom class can be used.

Earlier Java

Before Java 1.7, the standard way to do this is as follows:

import java.util.Random;

/**
 * Returns a pseudo-random number between min and max, inclusive.
 * The difference between min and max can be at most
 * <code>Integer.MAX_VALUE - 1</code>.
 *
 * @param min Minimum value
 * @param max Maximum value.  Must be greater than min.
 * @return Integer between min and max, inclusive.
 * @see java.util.Random#nextInt(int)
 */
public static int randInt(int min, int max) {

    // NOTE: This will (intentionally) not run as written so that folks
    // copy-pasting have to think about how to initialize their
    // Random instance.  Initialization of the Random instance is outside
    // the main scope of the question, but some decent options are to have
    // a field that is initialized once and then re-used as needed or to
    // use ThreadLocalRandom (if using at least Java 1.7).
    // 
    // In particular, do NOT do 'Random rand = new Random()' here or you
    // will get not very good / not very random results.
    Random rand;

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

    return randomNum;
}

See the relevant JavaDoc. In practice, the java.util.Random class is often preferable to java.lang.Math.random().

In particular, there is no need to reinvent the random integer generation wheel when there is a straightforward API within the standard library to accomplish the task.

Answer from Greg Case on Stack Overflow
🌐
freeCodeCamp
freecodecamp.org › news › generate-random-numbers-java
Java Random Number Generator – How to Generate Integers With Math Random
November 25, 2020 - In this article, we will learn how to generate pseudo-random numbers using Math.random() in Java.
🌐
GeeksforGeeks
geeksforgeeks.org › java › generating-random-numbers-in-java
Generating Random Numbers in Java - GeeksforGeeks
April 24, 2025 - Random Integers: 39 Random Integers: 190 Random Doubles: 0.4200728082969115 Random Doubles: 0.9327571841228275 ... Note: min and max are our lower and higher limit of number. ... // Generating random number in a specific range import java.io.*; ...
Discussions

How do I use java.util.Random to generate random integers within a given interval?
Look at the javadocs for java.util.Random . What does passing an argument to the Random constructor do? It sets the seed for that instance. Well what does that mean? For pseudo-random generators like java.util.Random you must set an initial seed which it uses to generate values. Providing the same seed will generate the same values in the same order. In your code you've set the seed to 25, which explains why you always get the same value. Is there a way to construct an instance of java.util.Random without providing a seed? More on reddit.com
🌐 r/learnjava
8
1
October 21, 2020
[Java] Generate random number, and assign to integer array, and then print?
So, you want to change a number range from 0 <- Range -> X |-------------------------------------| to 0 MIN <- Range -> MAX |-----------|---------------------------------| So, in the first case (0....X) what value would X need to have to produce the same range as MIN....MAX in the second case? Bear in mind that the highest number produced by .nextInt() is always 1 less than the number passed into the method. Work it out on paper. It involves only extremely elementary math. More on reddit.com
🌐 r/learnprogramming
15
17
March 30, 2018
🌐
Educative
educative.io › answers › how-to-generate-random-numbers-in-java
How to generate random numbers in Java
random.ints() provides an infinite stream of random integers within a specified range, allowing flexible and powerful random number generation in Java streams.
Top answer
1 of 16
4401

Java 7+

In Java 1.7 or later, the standard way to do this (generate a basic non-cryptographically secure random integer in the range [min, max]) is as follows:

import java.util.concurrent.ThreadLocalRandom;

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

See the relevant JavaDoc. This approach has the advantage of not needing to explicitly initialize a java.util.Random instance, which can be a source of confusion and error if used inappropriately.

However, conversely with ThreadLocalRandom there is no way to explicitly set the seed so it can be difficult to reproduce results in situations where that is useful such as testing or saving game states or similar.

Java 17+

As of Java 17, the psuedorandom number generating classes in the standard library implement the RandomGenerator interface. See the linked JavaDoc for more information. For example, if a cryptographically strong random number generator is desired, the SecureRandom class can be used.

Earlier Java

Before Java 1.7, the standard way to do this is as follows:

import java.util.Random;

/**
 * Returns a pseudo-random number between min and max, inclusive.
 * The difference between min and max can be at most
 * <code>Integer.MAX_VALUE - 1</code>.
 *
 * @param min Minimum value
 * @param max Maximum value.  Must be greater than min.
 * @return Integer between min and max, inclusive.
 * @see java.util.Random#nextInt(int)
 */
public static int randInt(int min, int max) {

    // NOTE: This will (intentionally) not run as written so that folks
    // copy-pasting have to think about how to initialize their
    // Random instance.  Initialization of the Random instance is outside
    // the main scope of the question, but some decent options are to have
    // a field that is initialized once and then re-used as needed or to
    // use ThreadLocalRandom (if using at least Java 1.7).
    // 
    // In particular, do NOT do 'Random rand = new Random()' here or you
    // will get not very good / not very random results.
    Random rand;

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

    return randomNum;
}

See the relevant JavaDoc. In practice, the java.util.Random class is often preferable to java.lang.Math.random().

In particular, there is no need to reinvent the random integer generation wheel when there is a straightforward API within the standard library to accomplish the task.

2 of 16
1520

Note that this approach is more biased and less efficient than a nextInt approach, https://stackoverflow.com/a/738651/360211

One standard pattern for accomplishing this is:

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

The Java Math library function Math.random() generates a double value in the range [0,1). Notice this range does not include the 1.

In order to get a specific range of values first, you need to multiply by the magnitude of the range of values you want covered.

Math.random() * ( Max - Min )

This returns a value in the range [0,Max-Min), where 'Max-Min' is not included.

For example, if you want [5,10), you need to cover five integer values so you use

Math.random() * 5

This would return a value in the range [0,5), where 5 is not included.

Now you need to shift this range up to the range that you are targeting. You do this by adding the Min value.

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

You now will get a value in the range [Min,Max). Following our example, that means [5,10):

5 + (Math.random() * (10 - 5))

But, this still doesn't include Max and you are getting a double value. In order to get the Max value included, you need to add 1 to your range parameter (Max - Min) and then truncate the decimal part by casting to an int. This is accomplished via:

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

And there you have it. A random integer value in the range [Min,Max], or per the example [5,10]:

5 + (int)(Math.random() * ((10 - 5) + 1))
🌐
Mkyong
mkyong.com › home › java › java – generate random integers in a range
Java - Generate random integers in a range - Mkyong.com
August 19, 2015 - Just change the values of 99,1,1 to your min and max to get your #s. If you use 99 as your max, randomly 99 + 1 will make the code generate 100, so if you really want max of 99, use 98 in this code. 😀 · * @author balcopc */ import java.util.Random; public class RandomNumberProj {
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Random.html
Random (Java Platform SE 8 )
1 week ago - Java™ Platform Standard Ed. 8 ... An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula. (See Donald Knuth, The Art of Computer Programming, Volume 2, Section 3.2.1.) If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.
Find elsewhere
🌐
Coderanch
coderanch.com › t › 650127 › java › create-simple-random-number-generator
How do I create a simple random number generator for the number between 1 -10? (Beginning Java forum at Coderanch)
There are a couple of ways in java. First in the class java.lang.Math it has a method random() that gives you a number between 0 and 1. You can multiply that to get the range you are after.
🌐
Vultr Docs
docs.vultr.com › java › standard-library › java › lang › Math › random
Java Math random() - Generate Random Number | Vultr Docs
September 27, 2024 - java Copy · double randomNumber ... it is executed. The value lies between 0.0 and 1.0. Use Math.random() in conjunction with type casting to generate a random integer....
🌐
Quora
quora.com › How-can-we-generate-random-integers-in-Java-using-random-function
How can we generate random integers in Java using random function? - Quora
Answer (1 of 13): There are two principal means of generating random (really pseudo-random) numbers: * the Random class generates random integers, doubles, longs and so on, in various ranges. * the static method Math.randomgenerates doubles between 0 (inclusive) and 1 (exclusive). To generate ...
🌐
Reddit
reddit.com › r/learnjava › how do i use java.util.random to generate random integers within a given interval?
r/learnjava on Reddit: How do I use java.util.Random to generate random integers within a given interval?
October 21, 2020 -

I am trying to generate a random number between 25 and 50, however every time I run my code, I keep getting 35. My teacher says it's because I planted a "seed" inside the Random declaration, but how would I change this into an interval?

import java.util.Random;

public class Range{

public static void main(String[] args) {

	`// TODO Auto-generated method stub`

Random rand = new Random(25);

int num = rand.nextInt(51);

System.out.println(num);

}

}

🌐
W3Schools
w3schools.com › java › java_howto_random_number.asp
Java How To Generate Random Numbers
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Server Java Syllabus Java Study Plan Java Interview Q&A Java Certificate ... You can use Math.random() method to generate a random number.
🌐
freeCodeCamp
freecodecamp.org › news › java-random-number-generator-how-to-generate-with-math-random-and-convert-to-integer
Java Random Number Generator – How to Generate Numbers with Math.random() and Convert to Integers
July 19, 2022 - So in this tutorial, I'll summarize the prominent use cases and how to choose the best-performing implementation based on your your Java code. In this article, you will learn: How to generate integers, floats, and booleans, How generate random numbers for performance-critical use cases, How generate random numbers for security-critical use cases, How numbers generators work, The differences between pseudo random number generators and true random number generators, How to use a seed to your advantage.
🌐
DigitalOcean
digitalocean.com › community › tutorials › random-number-generator-java
Random Number Generator in Java | DigitalOcean
August 4, 2022 - java.util.Random class can be used to create random numbers. It provides several methods to generate random integer, long, double etc.
🌐
Coderanch
coderanch.com › t › 742933 › java › Generating-random-number-ways
Generating random number different ways (Features new in Java 8 forum at Coderanch)
Suhaas Parekh wrote: 1. Why is the 2nd one generating numbers greater than 10 although I have passed the seed as 10 to the constructor of Random? You have misunderstood the function of a seed. The seed has nothing to do with the upper limit of numbers the PRNG (Pseudo Random Number Generator) will produce.
🌐
Oracle
docs.oracle.com › en › java › javase › 21 › docs › api › java.base › java › util › Random.html
Random (Java SE 21 & JDK 21)
January 20, 2026 - All 224 possible float values of ... positive integer less than 224, are produced with (approximately) equal probability. ... The hedge "approximately" is used in the foregoing description only because the next method is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm shown would choose float values from the stated range with perfect uniformity. [In early versions of Java, the result ...
🌐
Coderanch
coderanch.com › t › 371863 › java › Random-Number-Generator
Random Number Generator (Java in General forum at Coderanch)
September 28, 2003 - Is it going to be a while statement? class assmt2 { public static void main(String[] args)throws IOException{ Random generator = new Random(); int temp; System.out.println(" Enter Integers :"); //prompt user BufferedReader keyRead=new BufferedReader(new InputStreamReader(System.in)); int next=Integer.parseInt(keyRead.readLine()); for(int i=0; i<next; i++) //braces temp = generator.nextInt(1001); System.out.print(next); } }
🌐
Reddit
reddit.com › r/learnprogramming › [java] generate random number, and assign to integer array, and then print?
r/learnprogramming on Reddit: [Java] Generate random number, and assign to integer array, and then print?
March 30, 2018 -

I'm working on this challenging assignment outside of my Java course and given this objective:

"In a loop, generate a random party size, assign it to the waitingLine, and print it For generating the random party sizes, use the constants PARTY_SIZE_MIN and PARTY_SIZE_MAX to adjust the result you get when using the nextInt method

I don't understand how to use the min and max values however in tandem with Random variable...

        public static int PARTY_SIZE_MIN =1;
        public static int PARTY_SIZE_MAX=5;
        Random myRandom=new Random();
        int x = myRandom.nextInt(6); //max party size is 5
        Scanner keyboard = new Scanner(system.in);
        
        System.out.println("Enter the number of parties in the waiting line: ");
        int lineSize = keyboard.nextInt();
        
        int[] lineArray = new int[lineSize]; // made a new array to the size of the line input by the user
        
    
        for (int i = 0; i < lineSize; i++) {
        lineArray[i] = rand.nextInt(PARTY_SIZE_MAX-PARTY_SIZE_MIN)+1; //generate random numbers. upperbound-lowerbound, + 1 at end.

The numbers have to start a 1, not 0, which further complicates this... Any help is appreciated.

edit: Updated my code

🌐
Quora
quora.com › What-is-the-fastest-way-to-generate-a-random-number-in-Java-between-zero-and-one-billion
What is the fastest way to generate a random number in Java between zero and one billion? - Quora
Answer (1 of 2): In Java, the [code ]Random[/code] class is commonly used to generate random numbers. If you want to generate a random number between zero and one billion, you can use the [code ]nextInt[/code] method along with simple scaling ...
🌐
Medium
medium.com › @generativeai.saif › java-random-number-generator-5-methods-explained-with-examples-bf9e53abed3c
Java Random Number Generator: 5 Methods Explained with Examples | by Saif Ali | Medium
April 6, 2025 - Introduced in Java 8, the Random.ints() method provides a stream of random integers, which can be very useful when working with Java streams.