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
🌐
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 - 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. Let’s use the Math.random method to generate a random number in a given range [min, max):
Top answer
1 of 16
4402

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))
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
How can I generate Java random integers? - General Web Dev - SitePoint Forums | Web Development & Design Community
How can I generate Java random integers · It looks like you need help with Java, not JavaScript. I’ve moved this thread to the General Web Dev forum which is the best place for that · Okay, so since Math.random() will never return 1 we need to take that into account, otherwise we’ll never ... More on sitepoint.com
🌐 sitepoint.com
0
January 6, 2022
What is the best way to store an integer range in java?
Just store the min and max in separate int variables. That's the easiest approach. To generate the numbers to solve all you need to do is generate a random number in the range. Here, you can use the .nextInt() method from the Random class: Random rng = new Random(); // create a new Random generator instance int numberInRange = rng.nextInt((max + 1) - min) + min; The line int numberInRange = rng.nextInt((max + 1) - min) + min; generates a random number in the range min to max (inclusive). The parameter of the .nextInt() method is the maximum range excluded, so .nextInt(10) will generate random numbers in the range 0 to 9. By adding 1 to max I include max in the range, and then I subtract the min to get the range of possible numbers, that then need to be offset by adding min. As a concrete example: your range 10 to 100 inclusive Random rng = new Random(); // create a new Random generator instance int min = 10; int max = 100; int numberInRange = rng.nextInt((max + 1) - min) + min; When you calculate: max + 1, you get 101. Were you using this value as upper boundary for the .nextInt method, you'd get numbers in the range 0 to 100 inclusive. since you want 10 to 100 inclusive, you only have 91 distinct numbers, so you need to subtract the min (10) from the above result, 101 - 10 yields 91 Now, the .nextInt method produces numbers in the range 0 to 90 inclusive Last, by adding min to the random number generated above, you offset the range so that it goes from 10 to 100. Edit: optimally, you'd move the random number in range generation into its own method. My approach would be as follows: At class level (as a field): static Random rng = new Random(); The method itself: public static int rangedRandomInt(int min, int max) { return rng.nextInt((max + 1) - min) + min; } Or, with late initialisation At class level (as a field): static Random rng; The method itself: public static int rangedRandomInt(int min, int max) { if(rng == null) { // on-demand initialization of Random number generator rng = new Random(); } return rng.nextInt((max + 1) - min) + min; } More on reddit.com
🌐 r/learnprogramming
2
0
August 22, 2017
[Java] How do I get a random integer but exclude a specific one?
Arrays are a standard way to do this. You could also just change the direction by one for example if the result of random would make an enemy go back. More on reddit.com
🌐 r/learnprogramming
7
1
October 17, 2022
🌐
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.
🌐
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);

}

}

🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Random.html
Random (Java Platform SE 8 )
2 weeks ago - Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned.
🌐
GeeksforGeeks
geeksforgeeks.org › java › generating-random-numbers-in-java
Generating Random Numbers in Java - GeeksforGeeks
April 24, 2025 - // Generating random number using java.util.Random; import java.util.Random; public class Geeks{ public static void main(String[] args) { // Creating the instance of Random class Random r= new Random(); // Generate random integers in range 0 to 999 ...
Find elsewhere
🌐
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() ... 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....
🌐
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 - How can I generate Java random integers · It looks like you need help with Java, not JavaScript. I’ve moved this thread to the General Web Dev forum which is the best place for that · Okay, so since Math.random() will never return 1 we need to take that into account, otherwise we’ll never ...
🌐
Medium
medium.com › @AlexanderObregon › generating-random-numbers-in-java-within-a-range-7782d4cae298
Generating Random Numbers in Java Within a Range | Medium
August 18, 2025 - Internally, the generator works ... 0.0 and 1.0. To move that number into a specific range, you multiply it by the range size and then add the minimum....
🌐
Reddit
reddit.com › r/learnprogramming › what is the best way to store an integer range in java?
r/learnprogramming on Reddit: What is the best way to store an integer range in java?
August 22, 2017 -

I am making a math workout program and I need to prompt the user to input what digit range would he want in his math problem (using numbers from 0 to 9, from 10 to 100...).

I thought about making an int array (say I want addition problems that user numbers no bigger than 100 and no smaller than 0, id write int[] range = {0, 100}).

Then id use that array in generating numbers for the problem.

Is this the best way?

Top answer
1 of 2
5
Just store the min and max in separate int variables. That's the easiest approach. To generate the numbers to solve all you need to do is generate a random number in the range. Here, you can use the .nextInt() method from the Random class: Random rng = new Random(); // create a new Random generator instance int numberInRange = rng.nextInt((max + 1) - min) + min; The line int numberInRange = rng.nextInt((max + 1) - min) + min; generates a random number in the range min to max (inclusive). The parameter of the .nextInt() method is the maximum range excluded, so .nextInt(10) will generate random numbers in the range 0 to 9. By adding 1 to max I include max in the range, and then I subtract the min to get the range of possible numbers, that then need to be offset by adding min. As a concrete example: your range 10 to 100 inclusive Random rng = new Random(); // create a new Random generator instance int min = 10; int max = 100; int numberInRange = rng.nextInt((max + 1) - min) + min; When you calculate: max + 1, you get 101. Were you using this value as upper boundary for the .nextInt method, you'd get numbers in the range 0 to 100 inclusive. since you want 10 to 100 inclusive, you only have 91 distinct numbers, so you need to subtract the min (10) from the above result, 101 - 10 yields 91 Now, the .nextInt method produces numbers in the range 0 to 90 inclusive Last, by adding min to the random number generated above, you offset the range so that it goes from 10 to 100. Edit: optimally, you'd move the random number in range generation into its own method. My approach would be as follows: At class level (as a field): static Random rng = new Random(); The method itself: public static int rangedRandomInt(int min, int max) { return rng.nextInt((max + 1) - min) + min; } Or, with late initialisation At class level (as a field): static Random rng; The method itself: public static int rangedRandomInt(int min, int max) { if(rng == null) { // on-demand initialization of Random number generator rng = new Random(); } return rng.nextInt((max + 1) - min) + min; }
2 of 2
2
I agree with u/desrtfx . When you use an array (or some separate Range class) you’re creating a reference to a completely separate object, and one whose length is effectively unknown until the JRE starts optimizing. When you use two separate variables, their values are embedded directly in the body of their class or stack frame, and the compiler/JRE can see everything except the eventual run-time value beforehand. If you need to pass ranges around between methods or return them from a public method, you’ll either have to take two separate arguments as int min, int max or bite the bullet and come up with some class Range to bundle them up. You can also bundle two ints up into a long for internal passing-around, should the need arise: long bundle = (min & 0xFFFFFFFFL) | ((long)max << 32); int bundle_min = (int)bundle; int bundle_max = (int)(bundle >>> 32); In general—and Java makes this sort of hard in some places—it’s best to tie down your implementation as much as possible type-wise, so that neither you, nor users, nor other programmers can easily break things (e.g., by passing new int[0]). The types and variable names then serve as additional documentation, clarifying what the int values actually mean to the program.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Math › random
Math.random() - JavaScript | MDN
Use the Web Crypto API instead, and more precisely the Crypto.getRandomValues() method. function getRandomInt(max) { return Math.floor(Math.random() * max); } console.log(getRandomInt(3)); // Expected output: 0, 1 or 2 console.log(getRandomInt(1)); // Expected output: 0 console.log(Math.random()); // Expected output: a number from 0 to <1
🌐
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
Random (int, inclusive both): new Random().nextInt((max - min) + 1) + min; SecureRandom (secure int range): sr.nextInt((max - min) + 1) + min; Knowledge note: examples reflect APIs available through May 2024.
🌐
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.
🌐
Wyzant
wyzant.com › resources › ask an expert
Java Code - Math.random() range: 0.0 <= x < 1.
August 19, 2021 - Mr A. The purpose is to use Math.random() method only. And its range ranges between 0 <= x < 1. For example, suppose that I want 'x' to be between 0 <= x < 10, then I would use the following code: (int)(Math.random() * 10). ... Patrick B. I am using it.... look in the method GenerateRandom...
🌐
Quora
quora.com › How-do-you-generate-a-random-int-value-in-a-specific-range-What-should-be-done-code-code
How do you generate a random int value in a specific range? What should be done? [code ] [/code]
MsC in Chemistry & Java (programming language), IHBO West Brabant (Graduated 1987) · Author has 167 answers and 398.4K answer views · 7y · Using Math.random() double random = Math. random() * 49 + 1; or int random = (int )(Math.
🌐
DEV Community
dev.to › meenakshi052003 › generating-random-numbers-between-1-and-100-in-java-i3b
Generating Random Numbers Between 1 and 100 in Java - DEV Community
March 5, 2024 - When generating random numbers in a specified range, it's crucial to ensure that the upper bound is inclusive. The common mistake is to generate numbers up to nextInt(100), which would exclude 100.
🌐
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.
🌐
LabEx
labex.io › tutorials › java-how-to-generate-random-integers-within-a-specified-range-in-java-414035
How to generate random integers within a specified range in Java | LabEx
Generating random integers within a specified range is a fundamental skill in Java programming. This tutorial will guide you through the process, from understanding the basics of random number generation to applying it in practical use cases.
🌐
Mkyong
mkyong.com › home › java › java – generate random integers in a range
Java - Generate random integers in a range - Mkyong.com
August 19, 2015 - The console says “intstreams can’t be converted to int” ... This code is the easiest way to return 10 random numbers between 1 and 99. I took all your ideas and came up with this brief but effective code. 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 {