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 › generating-random-numbers-in-java
Generating Random Numbers in Java - GeeksforGeeks
April 24, 2025 - // Generating random number in a specific range import java.io.*; import java.util.*; class Geeks { public static void main (String[] args) { Random r = new Random(); int max=100,min=50; System.out.println("Generated numbers are within "+ min +" to "+ max); System.out.println(r.nextInt(max - min + 1) + min); System.out.println(r.nextInt(max - min + 1) + min); System.out.println(r.nextInt(max - min + 1) + min); } } ... The Math class contains various methods for performing various numeric operations such as, calculating exponentiation, logarithms etc.
🌐
W3Schools
w3schools.com › js › js_random.asp
W3Schools.com
// Return a random integer from ... number between 0 (inclusive) and 1 (exclusive). Example outputs: 0.0, 0.237, 0.9999, but never 1. Math.random() * 10 gives a range from 0 up to but not including 10....
🌐
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 - · Introduction to random numbers in Java ∘ Method 1: Using java.util.Random class ∘ Method 2: Using Math.random() method ∘ Method 3: Using ThreadLocalRandom class ∘ Method 4: Using Random.ints() method ∘ Method 5: Using SecureRandom for cryptographic applications · Generating random numbers within a specific range ∘ Using java.util.Random: ∘ Using Math.random(): ∘ Using ThreadLocalRandom: ·
🌐
Reddit
reddit.com › r/learnprogramming › generate a random number within a range - how does the math work?
r/learnprogramming on Reddit: Generate A Random Number Within A Range - How Does the Math Work?
February 4, 2022 -

Hi all,

I'm learning JS through FCC and it's going okay so far. I'm not a very mathematically inclined person, however, so I struggle with some concepts.

I'm struggling to understand how the following code works;

Math.floor(Math.random() * (max - min + 1)) + min

I tried writing out an example on paper and used 10 and 5 as max and min respectively.

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

wouldn't this mean that I can get numbers higher than the max though? Say I get a randomly generated 0.99; well 0.99 * (6) + 5 = 10.94 which is greater than my max of 10?

Am I doing this wrong?

🌐
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 - ... 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
🌐
Coderanch
coderanch.com › t › 622918 › java › convert-Math-random-generate-random
How can I convert Math.random to generate a random number between 1-1000 (Beginning Java forum at Coderanch)
October 31, 2013 - For example, to generate an integer between 0 and 9, you would write: int number = (int)(Math.random() * 10); By multiplying the value by 10, the range of possible values becomes 0.0 <= number < 10.0. Using Math.random works well when you need to generate a single random number.
🌐
CodeGym
codegym.cc › java blog › java math › java math random() method
Java Math random() Method
December 5, 2024 - The java.lang.Math.random() method returns a pseudorandom, “double” type number ranging from 0.0 to 1.0.Hence, the random number generated with the built-in method by Java always lies between 0 and 1.
🌐
Blogger
javarevisited.blogspot.com › 2013 › 05 › how-to-generate-random-numbers-in-java-between-range.html
How to Generate Random Numbers in Java Between Range - Example Tutorial
August 3, 2021 - Here is a Java code example of ... inclusive and 10 is exclusive. This code uses Math.random() method, which returns pseudo-random number in a range 0.0 to 1.0, where later is exclusive, by multiplying output with and then type casting into int, we can generate random integers ...
🌐
iO Flood
ioflood.com › blog › math-random-java
Java Math.random() Function: Number Generation Guide
February 29, 2024 - We began with the basics, explaining how to use Math.random() to generate random double values between 0.0 and 1.0. We then advanced to generating random numbers within a specific range and even generating random integers.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-math-random-method-examples
Java Math random() Method - GeeksforGeeks
December 20, 2025 - Since no seed is manually provided, ... from a given fixed range, we take a min and max variable to define the range for our random numbers, both min and max are inclusive in the range....
🌐
Wyzant
wyzant.com › resources › ask an expert
Java Code - Math.random() range: 0.0 <= x < 1.
August 19, 2021 - Java Code: Generating random numbers with Math.random() within a certain range. Math.random() range: 0.0
🌐
Vultr Docs
docs.vultr.com › java › standard-library › java › lang › Math › random
Java Math random() - Generate Random Number | Vultr Docs
September 27, 2024 - The random() method in Java's Math class is a fundamental tool for generating pseudo-random numbers between 0.0 (inclusive) and 1.0 (exclusive).
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Random.html
Random (Java Platform SE 8 )
1 week ago - However, subclasses of class Random are permitted to use other algorithms, so long as they adhere to the general contracts for all the methods. The algorithms implemented by class Random use a protected utility method that on each invocation can supply up to 32 pseudorandomly generated bits. Many ...
🌐
SitePoint
sitepoint.com › general web dev
How can I generate Java random integers? - General Web Dev - SitePoint Forums | Web Development & Design Community
January 6, 2022 - I tried the following: randomNum = minimum + (int)(Math.random() * maximum);. But it didn’t work for me.
🌐
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. Math.random() returns a double type pseudo-random number, greater than or equal to zero and less than one.
🌐
Mkyong
mkyong.com › home › java › java – generate random integers in a range
Java - Generate random integers in a range - Mkyong.com
August 19, 2015 - (int)(Math.random() * ((max - min) + 1)) + min · 2.2 Full examples to generate 10 random integers in a range between 16 (inclusive) and 20 (inclusive). TestRandom.java ·
🌐
Educative
educative.io › answers › how-to-generate-random-numbers-in-java
How to generate random numbers in Java
Math.random() produces a random double in the interval from 0 (inclusive) to 1 (exclusive). Ideal for straightforward random number generation and scaling to other ranges.
🌐
Studytonight
studytonight.com › java-examples › generating-random-numbers-in-a-range-in-java
Generating Random Numbers in a Range in Java - Studytonight
In this tutorial, we will learn ... random() method of the Math class is used to generate a decimal value between 0 and 1(0 inclusive, 1 exclusive)....