Java: Random numbers - API
Java provides the original Math.random method as well as the newer,
and more flexible, java.util.Random class.
Math.random
The Math.random() method
returns random numbers as double values in the range >=0.0 and <1.0 .
It returns the same result as the Random nextDouble() method (see below).
double x;
x = Math.random(); // assigns random number to x
java.util.Random class
To use the Random class create an
object of this class (giving a seed to the constructor if you wish),
then call one of the
methods below whenever you want a new random number. You must use one of
the following import statements:
import java.util.Random; // Only the Random class
import java.util.*; // All classes in the java.util package
Random constructors
Random x = new Random(); // default seed is time in milliseconds
Random x = new Random(long seed); // for reproducible testing
Random methods
The most common methods are those which get the next random number.
These methods all return a uniform distribution of values, except
nextGaussian().
In all of these examples, x is a Random object.
int x.nextInt(int n) // returns random int >= 0 and < n
int x.nextInt() // returns random int (full range)
long x.nextLong() // returns random long (full range)
float x.nextFloat() // returns random float >= 0.0 and < 1.0
double x.nextDouble() // returns random double >=0.0 and < 1.0
boolean x.nextBoolean() //returns random double (true or false)
double x.nextGaussian() //returns random number with mean 0.0
// and standard deviation 1.0
Example: Generating a random Color
You can create any color with values for red, green, and blue
(the RGB system) between 0-255. You could do it this way:
Random r = new Random();
Color c = new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256));
Although the three calls to nextInt(256) look the
same, each will return an independent random number.
Related pages
Random numbers - intro,
Random Numbers - shuffling