How to Generate Random Numbers

Young woman using laptop computer
Wonwoo Lee/Image Source/Getty Images

In the first article on generating random numbers, the focus was on generating whole numbers. Sometimes, however, it's useful to be able to generate random fractional numbers or even boolean values.

Generating a Random Number Between 0 and 1

There are two options to pick from when looking to generate a fractional number between 0 and 1. The first is to continue to use the Random object. The nextDouble() method will return a fractional number as a double data type:

 Random rand = new Random(); 
 Double pickedNumber = rand.nextDouble(); 

which will produce a number like:


Note: there is a nextFloat() method which will also give you a random fractional number except that instead of returning a double data type it returns a float.

Alternatively, there is a simpler way that doesn't involve the need to explicitly create a random number generator object. Instead, the random static method from the Math class can be used:

 double pickedNumber = Math.random(); 

Like the nextDouble() method the number produced is a double between 0 and 1:


There is no real difference between the two options because the Math.random() method creates a random number generator of its own. It just saves you having to do so yourself.

Generally, I use Math.random() if I don't already have a random object created. For example, if I wanted to generate a random fractional number between 30.0 and 40.0 then I would create a Random object and use both the nextInt() and nextDouble() methods:

 Random rand = new Random(); 
 int wholePart = rand.nextInt(10) + 30;
 double decimalPart = rand.nextDouble();
 double pickedNumber = wholePart + decimalPart;

Which will produce a number like:


How to Generate Random Boolean Values

There is one more method of the Random class that is worth looking at.

It is the nextBoolean() method. It produces a true or false with almost equal probability. For example, if I wanted to write a program that simulated the tossing of a coin fifty times I could do this:

 boolean headsOrTails;
 int headsCount = 0;
 int tailsCount = 0;
 Random rand = new Random(); 
 for (int j=0;j < 50;j++)
   headsOrTails = rand.nextBoolean();
   if (headsOrTails == true)
 System.out.println("The virtual coin landed on heads " + headsCount + " times and on tails " + tailsCount + " times."); 

After a bout of random virtual coin tossing, I might get a result of:

 The virtual coin landed on heads 27 times and on tails 23 times.