Suppose you wrote a program that prints the value of a number. You declared an int variable, initialized it to a value, then printed it.


Listing 1 - (version 1)

public class PrintNumber
    public static void main(String[] args)
        int x = 50;


Suppose you want your program to print a different number every time you run it. The program above will print the number 50 every time it is run. You would have to edit the program, change the literal 50 to a different value, then recompile the program for it to print a different value. Is it possible to have Java pick a different number each time you run the program? This is accomplished using the Random class.


Section 1 - The Random Class


The Random class generates pseudorandom numbers. The numbers are pseudorandom because the series starts at an arbitrary seed value. We can call its nextInt method to retrieve a random int value.

Random rand = new Random();
int x = rand.nextInt();



The random int generated above can have any value in the valid range of int values.


We can rewrite the PrintNumber program to print a random int value as follows:


Listing 2 - (version 2)


Copyright ©2017 by Ralph Lecessi Incorporated. All rights reserved.