Randomness in Java
Last updated
Last updated
In computer programming, true randomness is challenging to achieve because computers are fundamentally deterministic machines. Pseudorandom number generators (PRNGs) are used to simulate randomness by generating sequences of numbers that exhibit statistical properties similar to those of truly random sequences. The key distinction is that PRNGs are deterministic algorithms, meaning that the same initial state (seed) will produce the same sequence of numbers.
Import the Random library class
Create a Random object
Use the Random object's built-in methods
.nextBoolean()
generates either True or False at almost equal probability
.nextDouble()
generates a random number from 0.0 (inclusive) to 1.0 (exclusive)
.nextInt(int upperBound)
generates a random integer from 0 (inclusive) to upperBound (exclusive)
More can be found here.
This code assigns variable coin
to contain either true
or false
at every run of the program. True will dictate to the coin showing head; False will dictate to the coin showing tail.
This code is using rand.nextDouble()
and assigns it to variable num
. Everytime the random method is executed, it updates the variable with a new number from 0.0 to 1.0 (exclusively).
This code utilizes random integers to help grab a random item from an ArrayList.
The ArrayList called fruits
contains 7 items. Therefore, fruits.size()
returns 7.
rand.nextInt()
can only generate an integer from 0 to the given integer parameter. Therefore, it can only generate 0, 1, 2, 3, 4, 5, 6
in this situation given the size of the ArrayList as its parameter.
fruits.get(int i)
is an access method that returns an item located at the parameter index of i.
In this situation, it will grab a fruit at a randomly generated index of: 0, 1, 2, 3, 4, 5, 6