Resources ‎ > ‎ Java Basics ‎ > ‎

Random Number Generation

Java provides a random number generation class java.util.Random.  There are two Random constructors.  The first takes as input nothing and the second takes as input a seed value.  The easiest way to generate random numbers is with the nextInt method.  It takes as input an int and generates a number between 0 (inclusive) and the specified number (exclusive).  An example follows:

import java.util.Random;

class Test {

public static void main(String[] args) {

Random r = new Random();
int randnum = r.nextInt(25);

}
}

The example generates a number between 0 and 25.  In this example, 0 may be generated by the random number generator, but 25 will not be generated.

Notice that the first line of code is import java.util.Random .  This tells the compiler that the program will be using the Random class.  If you omit this line, your program will not compile.
Comments