Generate random numbers in Java between 0 and n
This post will discuss how to generate random numbers in Java between 0 and n, both inclusive.
1. Using Random class
The Random class from java.util package provides several methods to generate random numbers of different types, such as int, double, long, boolean, etc. We can create an instance of this class and invoke methods such as nextInt(), nextLong(), nextFloat(), nextDouble(), and nextBoolean() to get a pseudorandomly generated value of the corresponding type. These methods can optionally take an argument and return a value that is uniformly distributed between 0 and one minus the specified argument. They can also accept a range of numbers to be generated. For example, nextInt(n + 1) will generate a random number between 0 and n, and nextInt(m, n + 1) will generate a random number between m and n.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.Random; class Main { public static int generateRandomNumber(int n) { if (n < 0) { throw new IllegalArgumentException("n must not be negative"); } // generate a random number between `0` and `n` return new Random().nextInt(n + 1); } public static void main(String[] args) { int n = 5; System.out.println(generateRandomNumber(n)); } } |
Java 8 introduced several new methods to the Random class, which generates a stream of pseudorandom values. One such method is ints() that returns an unlimited stream of pseudorandom int values within the specified range. For example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import java.util.Random; class Main { public static int generateRandomNumber(int n) { if (n < 0) { throw new IllegalArgumentException("n must not be negative"); } // `Random.ints(0, (n + 1))` will generate stream of unlimited // pseudorandom numbers values between 0 and n // `findFirst()` returns an `OptionalInt` describing the first element // of this stream // `getAsInt()` returns the value is present in this `OptionalInt` return new Random().ints(0, n + 1) // IntStream .findFirst() // OptionalInt .getAsInt(); // int } public static void main(String[] args) { int n = 5; System.out.println(generateRandomNumber(n)); } } |
2. Using Math.random() method
Another option is to use the Math.random() that returns a pseudorandom double value greater than or equal to 0.0 and less than 1.0. It internally uses Random.nextDouble() and requires about twice the time for processing. We can tweak its return value to get a random number within a specific range. For example, the expression (int)(Math.random() * (n + 1)) generates a random number between 0 and n. It works as Math.random() generates a random double value in the range [0.0, 1.0). On multiplying it by n + 1, the lower limit remains 0, but the upper limit becomes in range (n, n + 1). Now on casting it with an int, the range becomes [0, n].
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Main { public static int generateRandomNumber(int n) { if (n < 0) { throw new IllegalArgumentException("n must not be negative"); } return (int)(Math.random() * (n + 1)); } public static void main(String[] args) { int n = 5; System.out.println(generateRandomNumber(n)); } } |
3. Using ThreadLocalRandom class
The ThreadLocalRandom class from the java.util.concurrent package is a subclass of the java.util.Random class for multithreaded environments. The use of this class in concurrent programs will typically result in better performance as a random number is now generated locally in the current thread, reducing the conflicts and the overhead. We can call the static method current() to get an instance of this class and then invoke methods such as nextInt(), nextDouble(), nextLong(), etc. Like Random class, these methods can optionally take one or two arguments to specify the range of the numbers to be generated. For example, nextInt(n + 1) will generate a random number between 0 and n and nextInt(m, n + 1) will generate a random number between m and n.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.util.concurrent.ThreadLocalRandom; class Main { public static int generateRandomNumber(int n) { if (n < 0) { throw new IllegalArgumentException("n must not be negative"); } return ThreadLocalRandom.current().nextInt(n + 1); } public static void main(String[] args) { int n = 5; System.out.println(generateRandomNumber(n)); } } |
4. Using SecureRandom Class
We can also use the SecureRandom class, which is a subclass of the java.util.Random class and provides a cryptographically strong random number generator. The SecureRandom class by default uses the RNG algorithm, when instantiated by using the default constructor. It inherits all the methods of the Random class, such as nextInt(), nextLong(), nextDouble(), etc. This class is available in the java.security package. Here is an example of how to use this class:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import java.security.SecureRandom; class Main { public static int generateRandomNumber(int n) { if (n <= 0) { throw new IllegalArgumentException("n must be positive"); } // obtains a `SecureRandom` instance via the no-argument constructor SecureRandom random = new SecureRandom(); // invoke generateSeed method to generate a given number of seed bytes byte[] bytes = random.generateSeed(20); // seed the `SecureRandom` instance with the specified seed bytes random.nextBytes(bytes); // `nextInt()` is inherited from `java.util.Random` class return random.nextInt(n + 1); } public static void main(String[] args) { int n = 5; System.out.println(generateRandomNumber(n)); } } |
5. Using Apache Commons Math library
With Apache Commons, we can construct a RandomDataGenerator instance using the supplied RandomGenerator or default random generator as the source of randomness. We can also use the RandomData implementation, but it is deprecated now. The following code example demonstrates its usage:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import org.apache.commons.math3.random.JDKRandomGenerator; import org.apache.commons.math3.random.RandomDataGenerator; class Main { public static int generateRandomNumber(int n) { if (n < 0) { throw new IllegalArgumentException("n must not be negative"); } return new RandomDataGenerator(new JDKRandomGenerator()).nextInt(0, n); } public static void main(String[] args) { int n = 5; System.out.println(generateRandomNumber(n)); } } |
That’s all about generating random numbers in Java between 0 and n.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)