Java Programming/Random numbers

To generate random numbers the  method can be used, which returns a, greater than or equal to 0.0 and less than 1.0.

The following code returns a random integer between n and m (where n <= randomNumber < m):

Alternatively, the  class provides methods for generating random s, s, s, s, s and 'Gaussians' (s from a normal distribution with mean 0.0 and standard deviation 1.0). For example, the following code is equivalent to that above:

As an example using random numbers, we can make a program that uses a Random object to simulate flipping a coin 20 times:

Of course, if you run the program you will probably get different results.

Truly random numbers
Both  and the   class produce pseudorandom numbers. This is good enough for a lot of applications, but remember that it is not truly random. If you want a more secure random number generator, Java provides the  package. What happens with  and the   class is that a 'seed' is chosen from which the pseudorandom numbers are generated. increases the security to ensure that the seed which is used by the pseudorandom number generator is non-deterministic &mdash; that is, you cannot simply put the machine in the same state to get the same set of results. Once you have created a  instance, you can use it in the same way as you can the   class.

If you want truly random numbers, you can get a hardware random number generator or use a randomness generation service.