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
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))
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-math-random-method-examples
Java Math random() Method - GeeksforGeeks
December 20, 2025 - To generate random integers in a range: (int)(Math.random() * (max - min + 1)) + min ... Math.random() is not suitable for cryptographic purposes. For better randomness and control, use java.util.Random or SecureRandom.
🌐
Vultr Docs
docs.vultr.com › java › standard-library › java › lang › Math › random
Java Math random() - Generate Random Number | Vultr Docs
September 27, 2024 - The code modifies the scaling factor to fit the random number within the desired range from min to max inclusive. The key is adjusting both the multiplication factor and the addition. Use Math.random() to simulate scenarios such as a coin toss where outcomes are binary.
🌐
Educative
educative.io › answers › how-to-use-the-mathrandom-method-in-java
How to use the Math.random() method in Java
The Math.random() method returns a pseudorandom number of data type double. The range of this random number is given by the following limit: · 0.0≤x<1.00.0\leq x <1.00.0≤x<1.0 where xxx is the random number
🌐
CodeGym
codegym.cc › java blog › java math › java math random() method
Java Math random() Method
December 5, 2024 - Then after taking a product of range with the Math.rand() you need to add the min number. After casting the double to an int, you have your random number within the specified range.
🌐
W3Schools
w3schools.com › java › ref_math_random.asp
Java Math random() Method
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 ... The random() method returns a random number between 0 and 1.
🌐
Baeldung
baeldung.com › home › java › java numbers › generating random numbers in a range in java
Generating Random Numbers in a Range in Java | Baeldung
May 11, 2024 - In this tutorial, we’ll explore different ways of generating random numbers within a range. Learn different ways of generating random numbers in Java. ... Learn how to generate random numbers in Java - both unbounded as well as within a given interval. ... Generate Bounded and Unbounded Random Strings using plain Java and the Apache Commons Lang library. ... Math.random gives a random double value that is greater than or equal to 0.0 and less than 1.0.
Find elsewhere
🌐
Quora
quora.com › How-can-random-numbers-in-a-range-be-generated-in-Java
How can random numbers in a range be generated in Java? - Quora
Math.random() returns a values between 0 and 1. It returns a double, but it will always be less than 1. Then we multiply that result by our range. So if our min is 3 and our max is 5, our range will be 3. With that, for a random value of .25, ...
🌐
Coderanch
coderanch.com › t › 680591 › java › generating-random-number-range
generating a random number in a range [Solved] (Beginning Java forum at Coderanch)
If you look at the api, Math.random() gives a double from 0 up to but not including 1, so multiply by for example 11 Math.random()*11 to get a number x where 0.0 <= x <11 Then, cast to an integer (int)(Math.random()*11) to get an integer 0 <= x <= 10 if what you needed was say 5 <= x <= 15 then finish off by adding 5.
🌐
Wyzant
wyzant.com › resources › ask an expert
Java Code: Generating random numbers with Math.random() within a certain range. Math.random() range: 0.0
August 19, 2021 - Mr A. Math.random() range: 0.0 <= x < 1. Generate a random integer "i" using *Math.random()* such that "i" is in the following range: 10 <= i < 20; 10 <= i <= 50. Write an expression using *Math.random()* that returns '0' or '1' randomly.
🌐
Programiz
programiz.com › java-programming › library › math › random
Java Math.random()
System.out.println(Math.random()); ... args) { int upperBound = 20; int lowerBound = 10; // upperBound 20 will also be included int range = (upperBound - lowerBound) + 1; System.out.println("Random Numbers between 10 and 20:"); for (int i = 0; i < 10; i ++) { // generate ...
🌐
Medium
medium.com › @AlexanderObregon › javas-math-random-method-explained-bafa91bf49a6
Java’s Math.random() Method Explained | Medium
November 30, 2024 - Adding 1 shifts the range to [1, 6]. ... This logic can be extended to simulate multiple dice or even weighted outcomes by adjusting the scaling factor or logic. Selecting a random item from a collection is a frequent task in programming, especially ...
🌐
Brainly
brainly.com › computers and technology › high school
How to use math. Random in java with a range. - brainly.com
September 30, 2023 - Determine the desired range of random numbers. Use the formula (Math.random() * (max - min + 1)) + min to generate a random number within the specified range.
🌐
Sentry
sentry.io › sentry answers › java › how do i generate random integers within a specific range in java?
How do I generate random integers within a specific range in Java? | Sentry
The Math class provides a random() method, but this method returns a double value from 0.0 (inclusive) to 1.0 (exclusive). This means we will have to write some additional code to generate an int value within our specified range.
🌐
Javatpoint
javatpoint.com › java-math-random-method
Java Math.random() Method
Java Math.random() Method with Examples on abs(), min(), max(), avg(), round(), ceil(), floor(), pow(), sqrt(), sin(), cos(), tan(), exp() etc.
🌐
Career Karma
careerkarma.com › blog › java › how to use java math.random
How to Use Java Math.random: A Step-By-Step Guide | Career Karma
December 1, 2023 - The Math.random()Java method generates a pseudorandom number between 0.0 and 1.0. The resulting random number can be multiplied to get a range outside 0-1, and the result can be 0 but is always less than 1.
🌐
Built In
builtin.com › articles › math.random-java
Java Math.random() Method Explained With Examples | Built In
June 23, 2025 - Why (max - min)? Because you want to define the width of the interval. Then you cast to int because Math.random() returns a double, and casting truncates the decimal part. Finally, you add min to shift the result into the desired range.
🌐
freeCodeCamp
freecodecamp.org › news › generate-random-numbers-java
Java Random Number Generator – How to Generate Integers With Math Random
November 25, 2020 - ... public static void main(String[] args) { double randomNumber = Math.random(); System.out.println(randomNumber); } // output #1 = 0.5600740702032417 // output #2 = 0.04906751303932033 · randomNumber will give us a different random number ...