How do I generate random integers within a specific range in Java?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Generating a random integer in Java is straightforward once you are clear about whether the upper bound is inclusive or exclusive. The best API also depends on context: ThreadLocalRandom is a strong default for most application code, while SecureRandom is the right choice for security-sensitive values.
The Most Common Need: Inclusive Range
Suppose you want a random integer from min through max, inclusive. With ThreadLocalRandom, the usual pattern is:
This works because nextInt(origin, bound) uses an inclusive lower bound and an exclusive upper bound. Adding 1 turns max into an inclusive endpoint.
Using Random
Random is also fine for many ordinary use cases.
The logic is:
- '
(max - min) + 1gives the number of possible values' - '
nextInt(...)picks an offset from0up to that count minus one' - adding
minshifts the result into the target range
Why ThreadLocalRandom Is Often Better
ThreadLocalRandom is especially good in concurrent code because it avoids shared Random contention.
A practical rule is:
- use
ThreadLocalRandomin ordinary multi-threaded application code - use
Randomwhen you want a simple explicitly owned generator instance
For modern server-side Java, ThreadLocalRandom is often the cleaner default.
Security-Sensitive Random Numbers Need SecureRandom
If the number is used for tokens, passwords, security codes, or anything adversarial, do not use Random or ThreadLocalRandom. Use SecureRandom.
This is slower than ordinary pseudo-random generation, but it is the right tool when unpredictability matters.
Inclusive And Exclusive Bounds Cause Most Bugs
Many mistakes come from forgetting that Java range APIs often use exclusive upper bounds.
For example:
This returns values from 10 through 19, not 20.
If you need the upper endpoint included, adjust accordingly.
A Reusable Helper Method
A helper method makes the contract explicit.
This is useful for dice rolls, test data, and bounded random selection.
What About Math.random()?
You can also do this with Math.random():
It works, but it is usually less explicit and less flexible than the dedicated random classes. In modern Java code, ThreadLocalRandom, Random, or SecureRandom are better choices.
Common Pitfalls
The most common mistake is forgetting whether the upper bound is inclusive or exclusive.
Another mistake is using Random for security-sensitive values. It is not designed for that.
Developers also sometimes forget to validate the range and end up with negative widths or min > max bugs.
Finally, using Math.random() everywhere can make intent less clear than using the dedicated random APIs.
Summary
- For an inclusive range, use
ThreadLocalRandom.current().nextInt(min, max + 1). - '
Randomis also valid for ordinary non-concurrent use.' - Use
SecureRandomfor security-sensitive values. - Be explicit about inclusive versus exclusive bounds.
- Wrap the logic in a helper method if the range generation appears often in your code.
Related reading
- How do I read / convert an InputStream into a String in Java?
- Java, How to get number of messages in a topic in apache kafka
- What is the difference between public, protected, package-private and private in Java?
- / and / in Java Comments
- (double colon) operator in Java 8
- Plus sign not encoded with RestTemplate using String URL, interpreted as space
- a bean of type 'org.springframework.mail.javamail.JavaMailSender' that could not be found
- A default binder has been requested, but there are no binders available for ''org.springframework.cloud.stream.messaging.DirectWithAttributesChannel''

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.