Random Numbers

To generate random numbers the Math.random method can be used, which returns a double, 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):

Example Code section 3.30: A random integer.
1   int randomNumber = n + (int)(Math.random * ( m - n ));

Alternatively, the java.util.Random class provides methods for generating random booleans, bytes, floats, ints, longs and 'Gaussians' (doubles from a normal distribution with mean 0.0 and standard deviation 1.0). For example, the following code is equivalent to that above:

Example Code section 3.31: A random integer with Gaussian.
1   Random random = new Random;
2   int randomNumber = n + random.nextInt(m - n);

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

Computer code Code listing 3.25: CoinFlipper.java
 1 import java.util.Random;
 3 public class CoinFlipper {
 5   public static void main(String[] args) {
 6     // The number of times to flip the coin
 7     final int TIMES_TO_FLIP = 20;
 8     int heads = 0;
 9     int tails = 0;
10     // Create a Random object
11     Random random = new Random;
12     for (int i = 0; i < TIMES_TO_FLIP; i++) {
13       // 0 or 1
14       int result = random.nextInt(2);
15       if (result == 1) {
16         System.out.println("Heads");
17         heads++;
18       } else {
19         System.out.println("Tails");
20         tails++;
21       }
22     }
23     System.out.println("There were "
24             + heads
25             + " heads and "
26             + tails
27             + " tails");
28   }
29 }
Computer code Possible output for code listing 3.25
There were 9 heads and 11 tails

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

Truly random numbers

Both Math.random and the Random 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 java.security.SecureRandom package. What happens with Math.random and the Random class is that a 'seed' is chosen from which the pseudorandom numbers are generated. SecureRandom increases the security to ensure that the seed which is used by the pseudorandom number generator is non-deterministic -- that is, you cannot simply put the machine in the same state to get the same set of results. Once you have created a SecureRandom instance, you can use it in the same way as you can the Random class.

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


To do:
Add some exercises like the ones in Variables

  This article uses material from the Wikipedia page available here. It is released under the Creative Commons Attribution-Share-Alike License 3.0.



Connect with defaultLogic
What We've Done
Led Digital Marketing Efforts of Top 500 e-Retailers.
Worked with Top Brands at Leading Agencies.
Successfully Managed Over $50 million in Digital Ad Spend.
Developed Strategies and Processes that Enabled Brands to Grow During an Economic Downturn.
Taught Advanced Internet Marketing Strategies at the graduate level.

Manage research, learning and skills at defaultLogic. Create an account using LinkedIn or facebook to manage and organize your Digital Marketing and Technology knowledge. defaultLogic works like a shopping cart for information -- helping you to save, discuss and share.

Visit defaultLogic's partner sites below:
PopFlock.com : Music Genres | Musicians | Musical Instruments | Music Industry
NCR Works : Retail Banking | Restaurant Industry | Retail Industry | Hospitality Industry

  Contact Us