Skip Top Navigation Bar

Using the Random Class

When we play games or run simulations, there is often an element of randomness involved. This makes each play through the game unique and more interesting. The Random class is one way that we can generate random values.

Random Constructor

In order to use the Random class, an object needs to be created.

Random randomGenerator = new Random();

Random Methods

We've compiled some helpful Random methods below.

A complete list of Random methods can be found in the Random API.

int nextInt()

This method returns a pseudorandom int value. All int values are possible with approximately equal probability.

int nextInt(int bound)

This method returns a pseudorandom int value between 0 (inclusive) and bound (exclusive). All values in this range have approximately equal probability.

int nextDouble()

This method returns a pseudorandom double value between 0.0 (inclusive) and 1.0 (exclusive).

int nextBoolean()

This method returns a pseudorandom boolean value either true or false.

Resources