class GenerateRandom {
public static void main( String args[] ) {
int min = 1; // Minimum value of range
int max = 10; // Maximum value of range
// Print the min and max
System.out.println("Random value in int from "+ min + " to " + max + ":");
// Generate random int value from min to max
int random_int = (int)Math.floor(Math.random() * (max - min + 1) + min);
// Printing the generated random numbers
System.out.println(random_int);
}
}
How to generate random numbers in Java
Key takeaways:
java.util.Randomgenerates random values in various formats.
Math.random()produces a randomdoublein the interval from 0 (inclusive) to 1 (exclusive). Ideal for straightforward random number generation and scaling to other ranges.
ThreadLocalRandomprovides thread-safe random number generation for integers, doubles, and booleans. It is best suited for multithreaded applications requiring efficient randomization.
random.ints()provides an infinite stream of random integers within a specified range, allowing flexible and powerful random number generation in Java streams.
SecureRandomproduces cryptographically secure random numbers. It is essential for applications needing high-level security, such as encryption and secure token generation.Each method caters to different needs, ranging from basic randomization to cryptographic security, allowing developers to select the appropriate tool for their specific use cases.
Random number generation
A random number is an arbitrary number that does not follow any specific pattern. John von Neumann introduced the first method in 1946 for
Random number generation can help us in gaming, such as controlling dice rolls
- Using the
java.util.Randomclass - Using the
Math.random()method - Using the
ThreadLocalRandomclass - Using the
Random.ints()method - Using the
SecureRandomclass
Method 1: Using the java.util.Random class
To use the Random class to generate random numbers, follow the steps below:
- Import the
java.util.Randomclass. - Make the instance of the
Randomclass, i.e.,Random rand = new Random(). - Ue some of the following
Randomclass methods onrandobject:nextInt(upperbound): This generates random integers in the range 0 toupperbound-1.nextFloat(): This generates a float between 0.0 and 1.0.nextDouble(): This generates a double between 0.0 and 1.0.
import java.util.Random;class GenerateRandom {public static void main( String args[] ) {// Instance of the random classRandom rand = new Random();// Setting the upper bound to generate the// random numbers in specific rangeint upperbound = 25;// Generating random numbers from 0 - 24// using nextInt()int int_random = rand.nextInt(upperbound);// Generating random numbers using nextDouble// in 0.0 and 1.0 rangedouble double_random = rand.nextDouble();// Generating random numbers using nextFloat// in 0.0 and 1.0 rangefloat float_random = rand.nextFloat();// Printing the generated random numbersSystem.out.println("Random integer value from 0 to " + (upperbound-1) + " : " + int_random);System.out.println("Random float value between 0.0 and 1.0 : " + float_random);System.out.println("Random double value between 0.0 and 1.0 : " + double_random);}}
This class also allows us to generate long and boolean-type random numbers using the nextLong() and nextBoolean() methods, respectively.
Method 2: Using the Math.random() method
The Java Math.random() method generates a random double-precision floating-point number between 0.
0 (inclusive) and 1.0 (exclusive).
class GenerateRandom {public static void main( String args[] ) {// Generate random numberSystem.out.println("Random number: " + Math.random());}}
For generating random numbers within a range using the Math.random(), follow the steps below:
- Declare the minimum value of the range.
- Declare the maximum value of the range.
- Use the formula
Math.floor(Math.random() * (max - min + 1) + min)to generate values, with theminand themaxvalue inclusive.
Note: This method can only be used if we need an integer or float of a specified random number range.
class GenerateRandom {public static void main( String args[] ) {int min = 50; // Minimum value of rangeint max = 100; // Maximum value of range// Print the min and maxSystem.out.println("Random value in int from "+ min + " to " + max + ":");// Generate random int value from min to maxint random_int = (int)Math.floor(Math.random() * (max - min + 1) + min);// Printing the generated random numbersSystem.out.println(random_int);}}
Method 3: Using the ThreadLocalRandom class
ThreadLocalRandom class in Java provides the mechanism to generate pseudorandom numbers in a safe thread model by providing each thread with its random number generator so that there is no conflict between the threads in the multithreaded environment. Additionally, this class uses an internally generated seed value that cannot be modified.
To use the ThreadLocalRandom class, follow the steps below:
- Import the
java.util.concurrent.ThreadLocalRandomclass. - Use some of the following
ThreadLocalRandomclass methods:- To generate a random integer, use
ThreadLocalRandom.current().nextInt(). - To generate a random double-precision floating-point number, use
ThreadLocalRandom.current().nextDouble(). - To generate a random boolean value, use
ThreadLocalRandom.current().nextBoolean().
- To generate a random integer, use
import java.util.concurrent.ThreadLocalRandom;class GenerateRandom {public static void main( String args[] ) {// Generate Java random integersint int_random = ThreadLocalRandom.current().nextInt();// Print Java random integersSystem.out.println("Random Integers: " + int_random);// Generate Java random doublesdouble double_rand = ThreadLocalRandom.current().nextDouble();// Print random doublesSystem.out.println("Random Doubles: " + double_rand);// Generate Java random booleanboolean boolean_rand = ThreadLocalRandom.current().nextBoolean();// Print Java random booleanSystem.out.println("Random Booleans: " + boolean_rand);}}
Method 4: Using the random.ints() method
The ints is an instance method of the Random class that is used to generate a stream of random integers in Java 8. There are four different variants of this method, namely:
ints(long streamSize): Generates a stream of pseudorandom random integers with the specified number of elements.ints(): Produces an infinite stream of random integers without any specific bounds or limits.ints(long streamSize, int randomNumberOrigin, int randomNumberBound): Generates a stream of pseudorandom integers with the specified number of elements. The value of each random integer is between a lower boundrandomNumberOrigin(included) and an upper boundrandomNumberBound(excluded).ints(int randomNumberOrigin, int randomNumberBound): Generates an infinite stream of pseudorandom integers that adhere to the provided lower bound (included) and upper bound (excluded).
import java.util.Random;public class Main{public static void main(String[] args) {//create an object of the Random classRandom random=new Random();// stream sizelong streamSize = 10;// using ints generate stream of random intsSystem.out.println("Random stream:");random.ints(streamSize).forEach(System.out::println);System.out.println("Range bound random stream:");random.ints(streamSize, 5, 11).forEach(System.out::println);}}
Method 5: Using the SecureRandom class
The Random class has a higher chance of repeating numbers during random number generation. But, the SecureRandom class mitigates the issue by allowing us to generate random numbers that are cryptographically strong using the following steps:
- Import
SecureRandomusingjava.security.SecureRandom. - Make the instance of the
SecureRandomclass usingnew SecureRandom(). - Use some of the following
SecureRandomclass methods onrandobject:nextInt(): This generates the next pseudorandomintvalue from the sequence of numbers maintained by theSecureRandomobject.nextInt(upperbound): This generates random numbers in the range 0 toupperbound-1.nextFloat(): This generates a float between 0.0 and 1.0.nextDouble(): This generates a double between 0.0 and 1.0.
Note: An article in the Nature magazine explains that for a pseudorandom number generator to be cryptographically secure, it must display two characteristics:
Pass statistical randomness tests: The numbers they generate need to look random and unpredictable.
Stay secure under attack: If a part of the initial or running state of the program becomes available due to an attack, a malicious actor should not be able to guess the other values based on the available information.
If a random number generator meets the above conditions, it would generate random sequences that have a high entropy, zero correlation, and no repetition of subsequences.
import java.security.SecureRandom;class GenerateRandom {public static void main( String args[] ) {// Instance of the SecureRandom classSecureRandom rand = new SecureRandom();// Setting the upper bound to generate// the random numbers between the specific rangeint upperbound = 1000;// Generating Java random numbers from 0 - 999// using nextInt()int int_random1 = rand.nextInt(upperbound);int int_random2 = rand.nextInt(upperbound);// Generating Java random numbers using nextDouble// in 0.0 and 1.0 rangedouble double_random = rand.nextDouble();// Generating Java random numbers using nextFloat// in 0.0 and 1.0 rangefloat float_random = rand.nextFloat();// Printing the generated Java random numbersSystem.out.println("Random integer value from 0 to " + (upperbound - 1) + " : " + int_random1);System.out.println("Random integer value from 0 to " + (upperbound - 1) + " : " + int_random2);System.out.println("Random float value between 0.0 and 1.0 : " + float_random);System.out.println("Random double value between 0.0 and 1.0 : " + double_random);}}
Selecting a suitable random number generation method
Each method meets different needs, from general randomization to high-security applications, allowing developers to choose the most suitable method based on their requirements. Choosing the right method for generating random numbers is key to ensure robustness in your applications, as Donald Knuth once said:
Note: Random numbers should not be generated with a method chosen at random.
Quiz!
Which class is preferred for generating random numbers in cryptographic applications?
java.util.Random
SecureRandom
ThreadLocalRandom
None of the above
Frequently asked questions
Haven’t found what you were looking for? Contact Us
How to generate random number between 1 to 10 in Java
What is Mersenne Twister?
What are true random numbers?
How to generate a 10-digit random number in Java
How to generate random string in JavaScript
What does RNG stand for?
What are the applications of random numbers?
What is a seed value?
What is random password generator?
What is a linear congruential generator (LCG)?
What is linear feedback shift register (LFSR)?
What is a seed selection?
What is random number generation hardware?
What are Monte Carlo methods?
What are some common UI elements for random number generation in apps?
Free Resources