Methods to Generate Random Numbers in Java
- Using Math.random() – Simple random numbers between 0.0 and 1.0
- Using java.util.Random – For more flexible number ranges
- Using ThreadLocalRandom – Better for multi-threaded programs
- Using SecureRandom – Ideal for secure, cryptographic needs
java.util.Random Class
The java.util.Random class is one of the most commonly used classes for generating random numbers in Java. It provides a wide range of methods to generate random values of different data types, such as integers, doubles, booleans, & more. To use the Random class, you first need to create an instance of it.
Here's an example:
import java.util.Random;
Random random = new Random();
Once you have an instance of the Random class, you can call various methods to generate random numbers. For example, to generate a random integer, you can use the nextInt() method:
int randomInt = random.nextInt();
This will give you a random integer between Integer.MIN_VALUE & Integer.MAX_VALUE. If you want to generate a random integer within a specific range, you can pass the upper bound as an argument to nextInt():
int randomInt = random.nextInt(100); // Generates a random integer between 0 (inclusive) & 100 (exclusive)
Similarly, you can use other methods like nextDouble(), nextLong(), nextBoolean(), etc., to generate random values of different data types.
Example
Java
import java.util.Random;
public class RandomExample {
public static void main(String[] args) {
Random random = new Random();
// Generating random integers
int randomInt = random.nextInt();
int randomIntRange = random.nextInt(100); // Range: 0 (inclusive) to 100 (exclusive)
// Generating random doubles
double randomDouble = random.nextDouble();
// Generating random booleans
boolean randomBoolean = random.nextBoolean();
System.out.println("Random Integer: " + randomInt);
System.out.println("Random Integer (Range): " + randomIntRange);
System.out.println("Random Double: " + randomDouble);
System.out.println("Random Boolean: " + randomBoolean);
}
}

You can also try this code with Online Java Compiler
Run Code
Output
Random Integer: 1198383132
Random Integer (Range): 41
Random Double: 0.045453200212297706
Random Boolean: false
Math.random() Method
Another way to generate random numbers in Java is by using the Math.random() method. This method is a static method of the Math class & returns a double value between 0.0 (inclusive) & 1.0 (exclusive).
For example :
double randomDouble = Math.random();
Since Math.random() returns a double value, you can multiply it by a desired range & cast it to an integer if needed. For example, to generate a random integer between 0 (inclusive) & 100 (exclusive), you can do the following:
int randomInt = (int) (Math.random() * 100);
One thing to keep in mind is that the Math.random() method uses a fixed seed value, which means that the sequence of random numbers generated will be the same every time you run the program. If you need more control over the seed value or want to generate different sequences of random numbers, you should use the Random class instead.
Example
Java
public class MathRandomExample {
public static void main(String[] args) {
// Generating random doubles
double randomDouble = Math.random();
// Generating random integers within a range
int randomIntRange = (int) (Math.random() * 100); // Range: 0 (inclusive) to 100 (exclusive)
System.out.println("Random Double: " + randomDouble);
System.out.println("Random Integer (Range): " + randomIntRange);
}
}

You can also try this code with Online Java Compiler
Run Code
Output
Random Double: 0.30783928138115846
Random Integer (Range): 38
ThreadLocalRandom Class
The ThreadLocalRandom class is a specialized random number generator introduced in Java 7. It is designed to provide random numbers in a thread-safe manner, making it suitable for use in multi-threaded environments. ThreadLocalRandom is similar to the Random class but offers better performance & scalability when used concurrently by multiple threads.
To use ThreadLocalRandom, you don't need to create an instance of it. Instead, you can directly call its static methods.
For example :
int randomInt = ThreadLocalRandom.current().nextInt();
The current() method returns the ThreadLocalRandom instance associated with the current thread, & then you can call methods like nextInt(), nextDouble(), etc., similar to the Random class.
ThreadLocalRandom also provides methods to generate random numbers within a specific range. For example, to generate a random integer between 1 (inclusive) & 100 (inclusive), you can use the following code:
int randomInt = ThreadLocalRandom.current().nextInt(1, 101);
Note that the upper bound is exclusive, so we pass 101 to include 100 in the range.
Using ThreadLocalRandom is recommended when you have multiple threads generating random numbers concurrently, as it eliminates contention & provides better performance compared to using a shared instance of the Random class.
Example
Java
import java.util.concurrent.ThreadLocalRandom;
public class ThreadLocalRandomExample {
public static void main(String[] args) {
// Generating random integers
int randomInt = ThreadLocalRandom.current().nextInt();
int randomIntRange = ThreadLocalRandom.current().nextInt(1, 101); // Range: 1 (inclusive) to 101 (exclusive)
// Generating random doubles
double randomDouble = ThreadLocalRandom.current().nextDouble();
// Generating random booleans
boolean randomBoolean = ThreadLocalRandom.current().nextBoolean();
System.out.println("Random Integer: " + randomInt);
System.out.println("Random Integer (Range): " + randomIntRange);
System.out.println("Random Double: " + randomDouble);
System.out.println("Random Boolean: " + randomBoolean);
}
}

You can also try this code with Online Java Compiler
Run Code
Output
Random Integer: 1727623638
Random Integer (Range): 68
Random Double: 0.8512023341504024
Random Boolean: true
Using SecureRandom for Cryptographic Use Cases
SecureRandom in Java is used for generating random numbers in security-sensitive applications. It is designed to be unpredictable and suitable for cryptographic tasks like creating secure passwords, session tokens, or encryption keys. Unlike the regular Random class, which produces predictable sequences if the seed is known, SecureRandom uses a strong algorithm that makes guessing difficult. This unpredictability is essential for preventing attacks in secure systems. Always use SecureRandom instead of Random when working with sensitive data or cryptographic processes.
How to Use SecureRandom in Java
Using SecureRandom is simple. Here's a basic example:
SecureRandom secureRandom = new SecureRandom();
int number = secureRandom.nextInt();
You can also generate secure random bytes like this:
byte[] bytes = new byte[16];
secureRandom.nextBytes(bytes);
This class is useful for creating random integers, secure tokens, or byte arrays for encryption. It ensures your data stays protected by using algorithms that reduce the risk of prediction or replay attacks in security systems.
Use Cases of SecureRandom
- Generating Secure OTPs or Tokens
SecureRandom helps create one-time passwords or session tokens that are hard to guess, protecting user accounts. - Creating Cryptographic Keys
It generates strong, random keys needed for encryption and decryption, making data access secure. - Seeding Encryption Algorithms
It provides safe seeds for encryption processes, ensuring data is encrypted in a secure and unique way each time.
These use cases help maintain privacy, prevent unauthorized access, and protect sensitive information.
Frequently Asked Questions
Can we set a custom seed value for random number generation in Java?
Yes, you can set a custom seed value using the setSeed() method of the Random class or by passing the seed value to the constructor.
Is there any difference in the quality of random numbers generated by different methods?
All three methods (Random class, Math.random(), & ThreadLocalRandom) use the same underlying algorithm & provide pseudorandom numbers of similar quality.
When should we use ThreadLocalRandom over the Random class?
ThreadLocalRandom is preferred in multi-threaded environments where multiple threads need to generate random numbers concurrently, as it provides better performance & thread safety compared to using a shared instance of the Random class.
Conclusion
In this article, we learned about three different ways to generate random numbers in Java: using the java.util.Random class, the Math.random() method, & the ThreadLocalRandom class. We discussed the usage & characteristics of each technique with the help of proper code examples to show their implementation. Random number generation is a fundamental concept in programming & is widely used in various scenarios such as simulations, games, & more.