Java Generate Random Number Between Two Given Values
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Java provides several ways to generate random numbers, and it's often necessary to generate random numbers within a specific range. In this article, we'll explore various methods to generate a random number between two given values in Java, providing technical explanations and examples.
Random Number Generation in Java
Before diving into the specifics of generating random numbers within a range, it's crucial to understand the basic tools available in Java:
java.util.Random: This utility class can generate various types of random data.Math.random(): A static method that generates a randomdoublebetween 0.0 (inclusive) and 1.0 (exclusive).ThreadLocalRandom: Suitable for use with multicore systems, providing better performance in concurrent environments.SecureRandom: This class provides a cryptographically strong random number generator.
Generating a Random Number Within a Range
To generate a random number within specified bounds [min, max], you'll want to leverage one of the above utilities while applying the correct mathematical transformation.
Method 1: Using java.util.Random
- Initialization: Create an instance of
Random. - Generate the Random Number: Use the instance method
nextInt(int bound)to get a number within a specific range.
Example:
Explanation: random.nextInt(max - min + 1) produces a number between 0 (inclusive) and (max - min + 1) (exclusive). By adding min, we shift the range to [min, max].
Method 2: Using Math.random()
Math.random() gives a double between 0.0 (inclusive) and 1.0 (exclusive), which can be scaled to the desired range:
Example:
Explanation: The expression (Math.random() * (max - min + 1)) stretches the 0.0 to 1.0 interval to a 0.0 to (max-min+1) interval. Casting to an int trims off the decimal, and adding min offsets the result to start at min.
Method 3: Using ThreadLocalRandom
ThreadLocalRandom is a better choice in a multi-threaded context, eliminating contention between threads.
Example:
Explanation: ThreadLocalRandom.current().nextInt(min, max + 1) directly generates a number in the required range, including min and max.
Method 4: Using SecureRandom
For security-sensitive applications, use SecureRandom.
Example:
Explanation: Works similarly to java.util.Random, but with stronger, cryptographically secure random numbers.
Key Points Summary
| Method | Thread Safety | Performance | Range Customization | Security |
Random | Not thread-safe | High | Easy to customize | Low |
Math.random() | Thread-safe | High | Needs manual scaling | Low |
ThreadLocalRandom | Thread-safe | Very high | Direct parameters | Medium |
SecureRandom | Thread-safe | Moderate | Similar to Random | High |
Additional Considerations
- Negative Ranges: All examples assume non-negative bounds. If you introduce negative bounds, ensure your logic reflects the correct range computation.
- Floating Point Numbers: When dealing with floating-point numbers, adjust by generating a
doubleand scaling similarly as shown.
Understanding these methods and selecting the appropriate one based on your application's requirements is crucial. You can prioritize speed, thread safety, or security as needed. Always remember, when security is a concern, SecureRandom is the preferred choice.
Related reading
- Java generics T vs Object
- Java Generics With a Class & an Interface - Together
- java get file size efficiently
- Java Get first item from a collection
- Java Get last element after split
- Java Get month Integer from Date
- Java Getting a substring from a string starting after a particular character
- Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

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.