Random Number Generator in Java
Java is a very versatile language which is used a lot within industry. It has the strength that it can virtually run on any platform, it is said to platform independent. This guide contains information on how to generate and manipulate random numbers in Java. We will step through two methods to generate random number in Java, the first one uses Math.random(), the second uses random class in Java.
Generate Random Number with Math.random()
To create a random number of the type double (decimal number), we simply write
double random = Math.random()
This will generate a number from 0 to 1, equally likely in this interval. The next question is, how to generate a random number in java between bounds? We now use two values for the upper and lower bound (value). We then have
double randomWithBounds = Math.random() * (upperBound) + lowerBound;
Where upperBound is the upper bound and lowerBound is the lower bound. Hence we multiply the random value by a constant, and add another constant.
Generate Random Number with Random Class
The second alternative is to use the Random class in Java.
import java.util.Random;
Random rand = new Random();
double random = rand.nextDouble(upperBound) + lowerBound;
Where upperBound is the upper bound and lowerBound is the lower bound.
Generate Random Integers (whole numbers) in Java
To generate random integers, whole number we can still use the same two methods.
Using the random class we have:
import java.util.Random;
Random rand = new Random();
int randomInteger = rand.nextInt(upperBound) + lowerBound;
Where upperBound is the upper bound and lowerBound is the lower bound.
Using the Math.random() method we should write:
int random = (int )(Math.random() * lowerBound+ upperBound);
Random Class or Math.random()?
It is generally said that it is better practice to use the Random class instead of Math.random. The Random class is more efficient and less biased. Biased means that the results might not be completely random.