Managing random numbers
Generating a truly random number is a big topic that does not belong to this book. But for the vast majority of practical purposes, the pseudo-random number generators provided by Java are good enough, and that is what we are going to discuss in this section.
There are two primary ways to generate a random number in Java Standard Library:
- The
java.lang.Math.random()
method - The
java.util.Random
class
There is also the java.security.SecureRandom
class, which provides a cryptographically strong random number generator, but it is outside the scope of an introductory course.
Method java.lang.Math.random()
The static method double random()
of the class Math
returns a double
type value greater than or equal to 0.0
and less than 1.0
:
for(int i =0; i < 3; i++){ System.out.println(Math.random()); //0.9350483840148613 //0.0477353019234189 //0.25784245516898985 }
We captured the result in the previous comments. But in practice, more often than not, a random integer from...