Welcome to our comprehensive guide on random number generation in Java! In this post, we will discuss 10 different ways to generate random numbers in Java. We will also provide working code snippets for each method. By the end of this post, you will be familiar with a variety of techniques for generating random numbers in Java and be able to choose the best method for your needs.
Whether you’re a programmer or a tester looking to enhance your skills, these coding snippets will unlock the secrets to seamless random number generation in your Java applications. Let’s dive in and discover the world of randomness in Java!
Let’s Get Started with Randon Number Generation in Java!
Here are the working Java programs for each of the 10 techniques to generate random numbers:
1. Using Math.random()
Method
The Math.random()
method returns a pseudo-random double value between 0.0 and 1.0. By scaling and adding an offset, you can generate random integers within a specified range.
public class MathRandomExample { public static void main(String[] args) { int range = 100; int minValue = 1; double randomValue = Math.random(); int randomNumber = (int)(randomValue * range) + minValue; System.out.println("Random Number (Math.random()): " + randomNumber); } }
Also Read: 1-10 Random Number Generator
2. Java Random
Class for Random Number Generation
The Random class provides a more flexible way to generate random numbers. It offers various methods like nextInt()
, nextLong()
, and nextDouble()
to generate integers, longs, and doubles, respectively.
import java.util.Random; public class RandomClassExample { public static void main(String[] args) { int range = 100; int minValue = 1; Random random = new Random(); int randomNumber = random.nextInt(range) + minValue; System.out.println("Random Number (Random class): " + randomNumber); } }
3. Using ThreadLocalRandom
(Java 7+)
The ThreadLocalRandom
class is a high-performance random number generator introduced in Java 7. It provides thread-local instances of Random, making it ideal for concurrent applications.
import java.util.concurrent.ThreadLocalRandom; public class ThreadLocalRandomExample { public static void main(String[] args) { int range = 100; int minValue = 1; int randomNumber = ThreadLocalRandom.current().nextInt(minValue, range + 1); System.out.println("Random Number (ThreadLocalRandom): " + randomNumber); } }
Also Read: Generate Random Images
4. Use SecureRandom
for Random Number Generation in Java
The SecureRandom
class is designed for generating cryptographically strong random numbers. It is crucial for sensitive applications like cryptography and secure communications.
import java.security.SecureRandom; public class SecureRandomExample { public static void main(String[] args) { int range = 100; int minValue = 1; SecureRandom secureRandom = new SecureRandom(); int randomNumber = secureRandom.nextInt(range) + minValue; System.out.println("Random Number (SecureRandom): " + randomNumber); } }
5. Using Random.nextInt()
(Java 8)
Java 8 introduced streams, and you can use Random.nextInt() within a stream to generate a random number from a specified range. This allows for a more concise and expressive coding style.
import java.util.Random; import java.util.stream.IntStream; public class RandomIntStreamExample { public static void main(String[] args) { int range = 100; int minValue = 1; Random random = new Random(); int randomNumber = random.ints(minValue, range + 1) .findFirst() .getAsInt(); System.out.println("Random Number (Java 8 Streams): " + randomNumber); } }
6. Random.ints()
for Random Number Generation in Java 9
Java 9 further simplified random number generation with the introduction of Random.ints()
, which directly returns a stream of random integers within a specified range.
import java.util.Random; public class RandomIntsExample { public static void main(String[] args) { int range = 100; int minValue = 1; Random random = new Random(); int randomNumber = random.ints(minValue, range + 1) .findFirst() .getAsInt(); System.out.println("Random Number (Java 9 Random.ints()): " + randomNumber); } }
7. Using Math.random()
and Thread.sleep()
for added randomness
By introducing a Thread.sleep()
delay, you can add an element of time-based randomness to the random number generation process. This approach can be helpful in specific scenarios.
public class RandomWithSleepExample { public static void main(String[] args) throws InterruptedException { int range = 100; int minValue = 1; double randomValue = Math.random(); int randomNumber = (int)(randomValue * range) + minValue; Thread.sleep(randomValue * 1000); // Add delay for added randomness System.out.println("Random Number (with added sleep): " + randomNumber); } }
8. Using java.util.BitSet
(Unique random numbers)
The BitSet class helps ensure that the generated random numbers are unique. This is useful when you need to create a unique set of random values without repetitions.
import java.util.BitSet; import java.util.Random; public class BitSetExample { public static void main(String[] args) { int range = 100; int minValue = 1; Random random = new Random(); BitSet bitSet = new BitSet(range); int randomNumber = random.nextInt(range); while (bitSet.get(randomNumber)) { randomNumber = random.nextInt(range); } bitSet.set(randomNumber); randomNumber += minValue; System.out.println("Random Number (BitSet): " + randomNumber); } }
9. Using Collections.shuffle()
with a List of numbers
By populating a list with a range of numbers and then shuffling it using Collections.shuffle()
, you can achieve random ordering of elements in the list.
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class CollectionsShuffleExample { public static void main(String[] args) { int range = 100; int minValue = 1; List < Integer > numbers = new ArrayList < > (); for (int i = minValue; i <= range; i++) { numbers.add(i); } Collections.shuffle(numbers); int randomNumber = numbers.get(0); System.out.println("Random Number (Collections.shuffle()): " + randomNumber); } }
Check this: How to Generate Random Numbers in Excel
10. Using UUID.randomUUID()
to generate a random UUID
Though originally intended for generating unique identifiers, you can leverage UUID.randomUUID()
to obtain random integer values by hashing the UUID.
import java.util.UUID; public class RandomUUIDExample { public static void main(String[] args) { int range = 100; int minValue = 1; UUID uuid = UUID.randomUUID(); int randomNumber = uuid.hashCode(); System.out.println("Random Number (UUID): " + randomNumber); } }
You can run each of these Java programs to see the output for generating random numbers using different methods.
By the way, if you love coding in Python, then you should also know how to generate a list of random numbers in Python.
Before You Leave
Now that you have an overview of the ten different ways to generate random numbers in Java, feel free to explore each method and choose the one that best suits your needs. Whether you’re working on simulations, games, or test automation, mastering the art of random number generation is a valuable skill for any Java programmer or tester.
Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Facebook) if you gained some knowledge from this tutorial.
Enjoy coding,
TechBeamers.