Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

8.4. Generating Random Variables

8.4.1. Problem

J2SE 1.4 includes a java.lang.Math class that provides a mechanism to get a random double value between 0.0 and 1.0, but you need to create random boolean values, or random int variables between zero and a specified number.

8.4.2. Solution

Generate random variables with Commons Lang RandomUtils, which provides a mechanism to generate random int, long, float, double, and boolean variables. The following code generates a random integer between zero and the value specified in the parameter to nextInt( ) :

import org.apache.commons.lang.math.RandomUtils;
// Create a random integer between 0 and 30
int maxVal = 30;
int randomInt = RandomUtils.nextInt( maxVal );

Or, if your application needs a random boolean variable, create one with a call to the static method nextBoolean( ):

import org.apache.commons.lang.math.RandomUtils;
 
boolean randomBool = RandomUtils.nextBoolean( );

8.4.3. Discussion

A frequent argument for not using a utility like RandomUtils is that the same task can be achieved with only one line of code. For example, if you need to retrieve a random integer between 0 and 32, you could write the following code:

int randomInt = (int) Math.floor( (Math.random( ) * (double) maxVal) );

While this statement may seem straightforward, it does contain a conceptual complexity not present in RandomUtils.nextInt(maxVal). RandomUtils.nextInt(maxVal) is a simple statement: "I need a random integer between 0 and maxVal"; the statement without RandomUtils is translated to a more complex statement:

I'm going to take a random double between 0.0 and 1.0, and multiply this number by maxVal, which has been cast to a double. This result should be a random double between 0.0 and maxVal, which I will then pass to Math.floor( ) and cast to an int.

While the previous statement does achieve the same task as RandomUtils, it does so by rolling-up multiple statements into a single line of code: two casts, a call to floor( ), a call to random() , and a multiplication. You may be able to instantly recognize this pattern as code that retrieves a random integer, but someone else may have a completely different approach. When you start to use some of the smaller utilities from Apache Commons systemwide, an application will tend toward greater readability; these small reductions in conceptual complexity quickly add up.


Creative Commons License
Common Java Cookbook by Tim O'Brien is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.
Permissions beyond the scope of this license may be available at http://www.discursive.com/books/cjcook/reference/jakartackbk-PREFACE-1.html. Copyright 2009. Common Java Cookbook Chunked HTML Output. Some Rights Reserved.