Generating Random Numbers Published: July 24, 2007 PrintEmail
An instance of java.util.Random 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.
There are two constructors for a Random object. The default constructor will create an object that uses the current time from your computer clock as the seed value for generating pseudo-random numbers. The other constructor accepts an argument of type long that will be used as the seed.
Random random = new Random(); // Sequence not repeatable Random random = new Random(88L); // Repeatable sequence
Beware of creating two generators in the same program with the default constructor if you use the default constructor.
The public methods provided by a Random object are:
Method Summary protected int next(int bits) Generates the next pseudorandom number. boolean nextBoolean() Returns the next pseudorandom, uniformly distributed boolean value from this random number generator's sequence. void nextBytes(byte[] bytes) Generates random bytes and places them into a user-supplied byte array. double nextDouble() Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence. float nextFloat() Returns the next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from this random number generator's sequence. double nextGaussian() Returns the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence. int nextInt() Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence. int nextInt(int n) Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. long nextLong() Returns the next pseudorandom, uniformly distributed long value from this random number generator's sequence. void setSeed(long seed) Sets the seed of this random number generator using a single long seed.
The following is the complete example
Random random = new Random(); // Random integers int i = random.nextInt(); // Random integers that range from from 0 to n int n = 20; i = random.nextInt(n+1);
byte[] bytes = new byte[4]; rand.nextBytes(bytes); long l = random.nextLong(); float f = random.nextFloat(); double d = random.nextDouble(); boolean b = random.nextBoolean();