A simple Java Random class example

As I was digging around through some code today, I found the following Java Random class example, and thought I'd share it here for anyone needed to see how to work with the Random class in Java. This example shows how to generate a random number in Java that is greater than or equal to 0, and less than 100:

import java.util.Random;

 * Create a random number that is greater than or equal to 0,
 * and less than 100. (It is set to run 20 tests.)
public class JavaRandomClassExample
  public static void main(String[] args)
    // run 20 random examples
    int numTests = 20;

    // create a new Java Random object
    Random random = new Random();
    for ( int i=0; i<numTests; i++ )
      // get the next random int
      int randomInt = random.nextInt(100);
      System.out.format("test %2d, randomInt = %d\n", i+1, randomInt );

Nothing too exciting here (except of course when you need a random class example), but here's some example output from an example random int test run:

test  1, randomInt = 46
test  2, randomInt = 94
test  3, randomInt = 80
test  4, randomInt = 61
test  5, randomInt = 81
test  6, randomInt = 85
test  7, randomInt = 99
test  8, randomInt = 80
test  9, randomInt = 11
test 10, randomInt = 68
test 11, randomInt = 57
test 12, randomInt = 80
test 13, randomInt = 7
test 14, randomInt = 68
test 15, randomInt = 25
test 16, randomInt = 77
test 17, randomInt = 96
test 18, randomInt = 26
test 19, randomInt = 12
test 20, randomInt = 59

If you ever need a random int in your own Java program, I hope this simple example is helpful.

The Random class nextInt method

The Random class nextInt method really does all the work in this example code. I can't describe the nextInt method any better than it's described in the Random class Javadoc, so here's a description from that documentation:

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.

The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All n possible int values are produced with (approximately) equal probability.

The Java Random class

If you need to generate other random values, including boolean, float, or long values, the Java Random class has other methods similar to this nextInt method, including these:

  1. next
  2. nextBoolean
  3. nextBytes
  4. nextDouble
  5. nextFloat
  6. nextGaussian
  7. nextLong

If you're going to use a Random class a lot, it helps to know about the concept of seeding a random class. Sun's Random class javadoc has a nice discussion of this, but this random class page by Doug Baldwin really provides a nice discussion of random numbers and seeds.