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.
Learn: Creating Objects and Calling Methods
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.
Your Turn
Let's try it in the Java Playground.
- Predict the range of values that can be generated.
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.
Your Turn
Let's try it in the Java Playground.
- Write a statement that will generate a random number between 1 and 6.
- Write a statement that will generate a random number between 10 and 50.
value is assigned a random int value between 0 and 9.
randomGrade is assigned a random int value between 1 and 100. The call intGenerator.nextInt(100) returns a random value between 0 and 99, then we add 1 to the value making the range of possible values 1 to 100.
int nextDouble()
This method returns a pseudorandom double value between 0.0 (inclusive) and 1.0 (exclusive).
Your Turn
Let's try it in the Java Playground.
- Predict the range of values that can be generated.
int nextBoolean()
This method returns a pseudorandom boolean value either true or false.
Your Turn
Let's try it in the Java Playground.
- Predict the range of values that can be generated.
Next Learn Tutorial
Learn: Using the String Class