O'Reilly logo

Java™ Phrasebook by Timothy Fisher

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Generating Random Numbers

Random rn = new Random();
											int value = rn.nextInt();
											double dvalue = rn.nextDouble();

To generate random numbers, we use the Random class found in the java.util package. By default, the Random class uses the current time of day as a seed value for its random number generator. You can also set a seed value by passing it as a parameter to the constructor of Random. The nextInt() method will produce a 32-bit integer random number.

An alternate way of generating random numbers is to use the random() method of the Math class in the java.lang package.

double value = Math.random();

This method will return a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. To generate a value within a specific ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required