Question
How can I generate a random int value within a specific range in Java?
The following approaches have problems related to correctness and integer overflow:
randomNum = minimum + (int)(Math.random() * maximum);
This is incorrect because randomNum can become larger than maximum.
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum = minimum + i;
This is also incorrect because randomNum can become smaller than minimum.
What is the correct way to generate a random integer between minimum and maximum in Java?
Short Answer
By the end of this page, you will understand how to generate random integers in Java safely and correctly for both inclusive and exclusive ranges. You will also learn why some common formulas fail, how Random.nextInt(bound) works, and when to use Random, ThreadLocalRandom, or Math.random().
Concept
Generating a random integer in a range means producing a whole number between two limits, such as from 5 to 10.
The key idea is:
- Find the size of the range
- Generate a random offset inside that range
- Shift that offset by the minimum value
For example, if the range is 5 to 10 inclusive, the possible values are:
5678910
That is 6 values total, so the range size is:
maximum - minimum + 1
Then you generate a random number from 0 up to rangeSize - 1, and add minimum.
In Java, the safest standard approach is usually:
Mental Model
Think of a random number in a range like picking a seat number in a row.
If seats go from 20 to 25, you do not directly guess a number from the whole world of integers. Instead:
- Count how many seats exist
- Pick a random position starting from
0 - Move that many seats forward from seat
20
So:
- seat range:
20to25 - total seats:
6 - random offset:
0to5 - final seat:
20 + offset
That is exactly how random integer range formulas work.
The mistake beginners often make is mixing up:
- the largest allowed value
- the size of the range
These are not the same thing.
Syntax and Examples
Basic inclusive range with Random
import java.util.Random;
Random random = new Random();
int minimum = 5;
int maximum = 10;
int randomNum = minimum + random.nextInt(maximum - minimum + 1);
System.out.println(randomNum);
This returns a value from 5 to 10, including both ends.
Why this works
random.nextInt(maximum - minimum + 1)
If minimum = 5 and maximum = 10, then:
maximum - minimum + 1 = 6
So nextInt(6) returns one of:
Step by Step Execution
Consider this code:
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random random = new Random();
int minimum = 3;
int maximum = 7;
int result = minimum + random.nextInt(maximum - minimum + 1);
System.out.println(result);
}
}
Step 1: Calculate the range size
maximum - minimum + 1
Substitute values:
7 - 3 + 1 = 5
So we need a random number from a set of 5 possible offsets.
Step 2: Generate the offset
Real World Use Cases
Picking a random item ID for testing
When generating sample user IDs, order numbers, or ticket numbers, you often need a random integer in a valid numeric range.
Game development
Games use random ranges for:
- dice rolls
- enemy damage
- loot drops
- random spawn coordinates
Example:
int damage = ThreadLocalRandom.current().nextInt(10, 21);
This produces damage from 10 to 20 inclusive.
Simulations
In simulations such as queues, traffic, or load testing, random integers help model variable behavior.
Picking a random array index
String[] names = {"Ana", "Ben", "Cara"};
int index = ThreadLocalRandom.current().nextInt(0, names.length);
System.out.println(names[index]);
This is one of the most common real uses of ranged random integers.
Temporary codes or tokens
For simple non-secure uses such as demo verification codes:
Real Codebase Usage
In real projects, developers usually wrap random range logic in a helper method instead of repeating formulas everywhere.
Helper method pattern
import java.util.concurrent.ThreadLocalRandom;
public static int randomInRange(int min, int max) {
if (min > max) {
throw new IllegalArgumentException("min must be <= max");
}
return ThreadLocalRandom.current().nextInt(min, max + 1);
}
This improves readability and reduces mistakes.
Guard clause for validation
A common pattern is checking inputs early:
if (min > max) {
throw new IllegalArgumentException("Invalid range");
}
This prevents hidden bugs later.
Configuration-driven ranges
Applications often read limits from config files or environment variables:
int minRetries = 1;
;
ThreadLocalRandom.current().nextInt(minRetries, maxRetries + );
Common Mistakes
1. Using maximum instead of range size
Broken code:
int randomNum = minimum + (int)(Math.random() * maximum);
Why it is wrong:
maximumis the upper value, not the number of possible values- this can create numbers above the allowed maximum
Correct version:
int randomNum = minimum + (int)(Math.random() * (maximum - minimum + 1));
2. Using % to limit random numbers
Broken code:
int i = random.nextInt() % n;
Why it is wrong:
- results can be negative
- distribution may be uneven
Correct version:
int i = random.nextInt(n);
Comparisons
| Approach | Example | Range Style | Good Choice? | Notes |
|---|---|---|---|---|
Math.random() | min + (int)(Math.random() * (max - min + 1)) | Inclusive with manual formula | Sometimes | Works, but less explicit |
Random.nextInt(bound) | min + random.nextInt(max - min + 1) | Inclusive with manual shift | Yes | Classic and common |
ThreadLocalRandom.nextInt(min, maxExclusive) | ThreadLocalRandom.current().nextInt(min, max + 1) | Upper bound exclusive | Yes | Very convenient, common in modern Java |
Cheat Sheet
// Inclusive range: [min, max]
int value = min + random.nextInt(max - min + 1);
// Inclusive range with ThreadLocalRandom
int value = ThreadLocalRandom.current().nextInt(min, max + 1);
// Exclusive upper bound: [min, max)
int value = ThreadLocalRandom.current().nextInt(min, max);
// Math.random() version for inclusive range
int value = min + (int)(Math.random() * (max - min + 1));
Rules to remember
nextInt(bound)returns0tobound - 1- To include
max, usemax - min + 1 - Do not use
%to force a random value into a range - Validate that
min <= max - Watch out for overflow when using
max + 1 - Use
SecureRandomfor security-sensitive values
FAQ
How do I generate a random integer between two numbers in Java?
Use:
int value = min + random.nextInt(max - min + 1);
This gives a value from min to max inclusive.
Why does random.nextInt() % n give wrong results?
Because random.nextInt() can be negative, and % n can also be negative. It can also produce uneven distribution.
Is Math.random() okay for generating random integers?
Yes, if used correctly with the proper range formula. But Random or ThreadLocalRandom is usually clearer.
What is the easiest modern Java way to generate a number in a range?
ThreadLocalRandom.current().nextInt(min, max + 1)
This is very readable for inclusive ranges.
Is the upper bound included in nextInt(bound)?
No. The upper bound is exclusive.
Mini Project
Description
Build a small Java program that simulates rolling a custom die. The user chooses a minimum and maximum value, and the program generates a random integer in that inclusive range. This demonstrates correct range calculation, input validation, and repeated random generation.
Goal
Create a reusable method that returns a random integer between min and max inclusive, then use it to print several sample results.
Requirements
[
"Create a method that accepts min and max as parameters.",
"Validate that min is less than or equal to max.",
"Generate a random integer in the inclusive range.",
"Call the method multiple times and print the results.",
"Use standard Java random utilities rather than manual modulo logic."
]