Generating random numbers in Java
The random number can be generated using different ways.
java.util.Random class is used to generate random numbers for different data types such as boolean, int, long, float, and double.
An object of Random class is initialized and the method nextInt(), nextDouble() or nextLong() is used to generate random number. java.util.Random
An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula.
If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.
In order to guarantee this property, particular algorithms are specified for the class Random. Java implementations must use all the algorithms shown here for the class Random, for the sake of absolute portability of Java code.
However, subclasses of class Random are permitted to use other algorithms, so long as they adhere to the general contracts for all the methods.
1). Using the Math.random method to generate a random number
public int generateRandomNumber(int min, int max) {
return (int) ((Math.random() * (max - min)) + min);
}
2). Using the java.util.Random.nextInt
public int generateRandomNumberUsingNextInt(int min, int max) {
Random random = new Random();
return random.nextInt(max - min) + min;
}
3). Java Random number between 1 and 10
import java.util.Random;
public class generateRandomNumber {
public static void main(String[] args) {
Random random = new Random();
int rand = 0;
while (true) {
rand = random.nextInt(11);
if (rand != 0) break;
}
System.out.println(rand);
}
}
output:
5
4). Generate Random number for given data types
import java.util.Random;
import java.util.Arrays;
public class generateRandomNumber {
public static void main(String[] args) {
Random random = new Random();
double d = random.nextDouble();
double d1 = Math.random();
float f = random.nextFloat();
long l = random.nextLong();
boolean flag = random.nextBoolean();
byte[] randomByteArray = new byte[5];
random.nextBytes(randomByteArray);
System.out.println("double: " + d1);
System.out.println("float: " + f);
System.out.println("long :" + l);
System.out.println("flag :" + flag);
System.out.println("Random Byte Array : " + Arrays.toString(randomByteArray));
}
output:
double: 0.9650131045802527
float: 0.19712901
long :6559100913408573531
flag :true
Random Byte Array : [-55, 83, 56, -11, 71]
5). Generate a random number in a multithreaded environment
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
public class RandomForThreadLocal {
public static void main(String[] args) {
Runnable runnable = new MyRunnable();
for (int i = 0; i < 10; i++) {
Thread t = new Thread(runnable);
t.setName("Running-Thread-" + i);
t.start();
}
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " : " + ThreadLocalRandom.current().nextInt());
}
}
output:
Running-Thread-8 : -387795467
Running-Thread-6 : -195386630
Running-Thread-9 : 1434141147
Running-Thread-3 : -398065027
Running-Thread-1 : -1087577176
Running-Thread-2 : -1891538242
Running-Thread-5 : -1042722406
Running-Thread-4 : -574451569
Running-Thread-0 : -634652647
Running-Thread-7 : -129036719
6). SecureRandom
This class provides a cryptographically strong random number generator (RNG). A cryptographically strong random number minimally complies with the statistical random number generator tests specified in FIPS 140-2, Security Requirements for Cryptographic Modules, section 4.9.1. Additionally, SecureRandom must produce non-deterministic output.
Therefore any seed material passed to a SecureRandom object must be unpredictable, and all SecureRandom output sequences must be cryptographically strong, as described in RFC 1750: Randomness Recommendations for Security.
A caller obtains a SecureRandom instance via the no-argument constructor or one of the getInstance methods:
SecureRandom random = new SecureRandom();
Many SecureRandom implementations are in the form of a pseudo-random number generator (PRNG), which means they use a deterministic algorithm to produce a pseudo-random sequence from a true random seed. Other implementations may produce true random numbers, and yet others may use a combination of both techniques.
Typical callers of SecureRandom invoke the following methods to retrieve random bytes:
SecureRandom random = new SecureRandom();
byte bytes[] = new byte[20];
random.nextBytes(bytes);
import java.util.Random;
import java.security.SecureRandom;
public class RandomForThreadLocal {
public static void main(String[] args) {
SecureRandom random = new SecureRandom();
byte bytes[] = new byte[20];
random.nextBytes(bytes);
byte seed[] = random.generateSeed(20);
System.out.println(bytes);
}
}
output:
[B@5cad8086
In this article, we have seen different ways of Generating random numbers in Java using different ways. All source code in the article can be found in the GitHub repository
0 Comments
Post a Comment