Java random numbers
Random numbers from very low to very high ranges can be generated with Java.
This tutorial focuses on:
- The random() method
- The Random class
- The psuedorandom process
- Setting a seed
The random() method
Generate random numbers using the random() method of the Math class. Random numbers returned will be of data type double from 0.0(inclusive) to 1.0(exclusive) - meaning that the random number generated will be greater than or equal to 0.0 and less than 1.0.
Why limit yourself to such a low range as between 0.0 and 1.0? You can actually return random numbers in any range. To do this multiply the returned value from a random() function by a number that when added to the lowest number in your range will produce the highest range. If this sounds confusing, not to worry, here is an example:
The random() method returns decimal numbers, but you can also return whole numbers. This is accomplished by data type casting the value returned by the Math.random() method to data type int.
Placing the word int like that in parentheses before the random() function and also placing the random() function in parentheses will convert the value returned by the random() function from a double to a whole number. This process is known as casting.
Using the Random class to generate random numbers
The Random class is located in the java.util package. It can be used generate random numbers of different data types (double, float, int, long) as well as random booleans.
Methods of the Random class:
- nextInt() - returns a random number of data type int.
- nextInt(int n) - returns a random number of data type int ranging from 0(inclusive) to n(exclusive)
- nextDouble() - returns a random double ranging from 0.0(inclusive) to 1.0(exclusive)
- nextBoolean() - returns a random boolean (true/false value)
NOTE: When you use Math.random() to generate a random double, it actually creates a Random object and calls the nextDouble() method.
The psuedorandom process
It seems that these random numbers (and other random values) are really random, but they are not. The Random class actually generates pseudorandom numbers - numbers generated in a non random way, but in a way that makes them look random. This is accomplished by the Random class taking an initial value (called a seed) and through a specific algorithm generating another value based on the seed.
By default, the seed given to a Random object is the value of the system clock in milliseconds (which is your computer's interpretation of the current time). Since this is constantly changing, the seed is always changing and therefore a different "random" number is always being generated.
If you set the seed yourself to a fixed number, then the "random" numbers generated will always be the same like in this example below.