COMP2511
Random Numbers in Java
Randomness
Randomness is also useful
• in computer games:
• may want aliens to move in a random pattern
• the layout of a dungeon may be randomly generated
• may want to introduce unpredictability
• in physics/applied maths:
• carry out simulations to determine behaviour
• e.g. models of molecules are often assume to move randomly
• in testing:
• stress test components by bombarding them with random data
• random data is often seen as unbiased data
• gives average performance (e.g. in sorting algorithms)
• in cryptography
COMP2511: Random Numbers 2
Random Numbers
How can a computer pick a number at random?
• it cannot !
Software can only produce pseudo random numbers.
• a pseudo random number is one that is predictable
• (although it may appear unpredictable)
⇒ Implementation may deviate from expected theoretical behaviour
COMP2511: Random Numbers 3
Generating Random Numbers in Java
Using random class,
• Need to import the class java.util.Random
• Option-1: Creates a new random number generator.
Random rand = new Random();
• Option-2: Creates a new random number generator using a single long seed. Every time you run a
program with the same seed, you get exactly the same sequence of ‘random’ numbers.
Random rand = new Random(long seed);
• To vary the output, we can give the random seeder a starting point that varies with time. For
example, a starting point (seed) is the current time.
• Go to the API for more information at
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Random.html
COMP2511: Random Numbers 4
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Random.html