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 pseudo-random numberPseudo-random numbers are developed by a mathematical formula or an algorithm in which a series of numbers is produced from an initial seed value. The algorithms are deterministic, so if the ‘seed’ value is used again, the sequence of random numbers will be similar each time. generation known as middle-square method.
Random number generation can help us in gaming, such as controlling dice rolls OTPOne-time password codes, and in cryptography for generating secure keys and encryption. Java provides several built-in ways to create random numbers, and Java random numbers can be of various types, such as integers and doubles of the specified range. In this Answer, we’ll explore five different methods for Java random number generators.
- Using the
java.util.Random
class
- Using the
Math.random()
method
- Using the
ThreadLocalRandom
class
- Using the
Random.ints()
method
- Using the
SecureRandom
class
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.Random
class.
- Make the instance of the
Random
class,
i.e.,
Random rand = new Random()
.
- Ue some of the following
Random
class methods on rand
object:
nextInt(upperbound)
: This generates random integers in the range 0 to upperbound-1
.
nextFloat()
: This generates a float between 0.0 and 1.0.
nextDouble()
: This generates a double between 0.0 and 1.0.