The “Math.random()” is an inbuilt static function of the “java.lang.Math” class. This method retrieves a positive double value between the range “0.0” (inclusive) to “1.0” (exclusive). It returns a double value, however, you can typecast it to int or long (if needed). In addition to this, you can modify this method according to your preferences to generate a random number between a specific range.
This blog post will show you how to generate random numbers in Java using the “Math.random()” method.
How to Use Math.random() in Java
To use this method in your Java program, first import the Math class and then invoke the random() method using the Math class as follows:
Math.random();
Whenever a user invokes the “Math.random()” method, it generates a pseudorandom number in the range “0.0 <= num < 1.0”.
Example 1: Using Math.random() to Generate a Random Number
Let’s create a class named “JavaRandomNumbers” and import the Math class at the start of your program:
import java.lang.Math;
public class JavaRandomNumbers {
public static void main(String[] args) {
double randomNum = Math.random();
System.out.println("The Generated Random Number ⇒ " + randomNum);
}
}
In the main() method, we invoke the random() method and store the result in a double-type variable “randomNum”. After this, we print the randomly generated value on the console using the println() method:
From the above output, you can notice that we run the code multiple times and each time the random() method generates a unique random value.
Example 2: Getting/Generating a Random Number From 0 to a Specific Range Using Math.random()
To get a random number between 0 and a specific range, you must multiply the outcome of the random() method by the size/magnitude of the range. For instance, the below code generates a random number between 0.0 and 14.0:
import java.lang.Math;
public class JavaRandomNumbers {
public static void main(String[] args) {
double randomNum = Math.random()*14;
System.out.println("The Generated Random Number ⇒ " + randomNum);
}
}
We execute the random() method several times, as a result, each time it generates a unique random number between 0 and 14:
Example 3: Using Math.random() to Generate a Random Integer
By default, the random() method retrieves a double-type value. To get a random integer using the random() method, you must cast the retrieved random value to a respective data type, as shown in the following code:
import java.lang.Math;
public class JavaRandomNumbers {
public static void main(String[] args) {
int randomNum = (int) (Math.random()*14);
System.out.println("The Generated Random Number ⇒ " + randomNum);
}
}
The above code will generate a random integer between 0(inclusive) and 14(exclusive):
The output demonstrates that the random() method generates a random integer each time we run the program.
Example 4: Using Math.random() to Generate a Random Integer Between a Range
Sometimes users may need to generate a random integer between a specific range (especially while developing a game). In such cases, first, find the range, multiply it with the result of Math.random(), and add the resultant value to the starting range:
import java.lang.Math;
public class JavaRandomNumbers {
static int generateRandomNum(int minRange, int maxRange){
int findRange = (maxRange - minRange) + 1;
return (int)(Math.random() * findRange) + minRange;
}
public static void main(String[] args) {
int randomNum = generateRandomNum(5, 14);
System.out.println("The Generated Random Number ⇒ " + randomNum);
}
}
In this code,
- We create a user-defined function “generateRandomNum()” that accepts two arguments: “minRange” and “maxRange”.
- Within this function, we compute the range by subtracting the minRange from the maxRange and adding “1” in the resultant range.
- After this, we invoke the “Math.random()”, typecast the retrieved value to int, and multiply it with the computed range. Also, we add the minRange in the resultant value to generate a random value between the specified range.
- Finally, the “generateRandomNum()” function retrieves a random integer within the specified/given range.
Example 5: Choosing Random Numbers From an Array Using Math.random()
You can also invoke the random() method on an array to get random numbers from it. For instance, in the below code, we have an integer-type array that contains seven elements. Suppose we want any three random array elements. For this purpose, we use the random() method as follows:
import java.lang.Math;
import java.util.Arrays;
public class JavaRandomNumbers {
public static void main(String[] args) {
int[] inputArr = { 120, 231, 45, 54, 122, 113, 125 };
System.out.println("The Array Elements are ⇒ " + Arrays.toString(inputArr));
System.out.println("Three Random Array Elements are ⇒ ");
for (int i = 0; i < 3; i++) {
int randomElement = (int) (Math.random() * inputArr.length);
System.out.println(inputArr[randomElement]);
}
}
}
- First, we define an array with integer values and print it on the console.
- After this, we use the for loop to specify the number of elements to be fetched, i.e., 3.
- Finally, we invoke the random() method, multiply it with the array length, and typecast it to int. Doing this will fetch the random elements from the input array, which we print on the console using println():
Alternatives of Math.random() in Java
“Math.random()” is not the only way of generating random numbers in Java, instead we have some other alternatives available that are discussed below:
1. java.util.Random Class
The Random class of the “util” package helps us generate pseudorandom numbers of different types, such as Integer, double, etc. For this purpose, it offers different methods like nextInt() and nextDouble().
Let’s import this class from the respective package at the start of the program and create its object in the main() method:
import java.util.*;
public class JavaRandomNumbers {
public static void main(String args[])
{
Random rand = new Random();
int randomInt = rand.nextInt(50);
System.out.println("The Random Integer is ==> "+ randomInt);
double randomDub = rand.nextDouble();
System.out.println("The Random Double is ==> "+ randomDub);
}
}
Now use the nextInt() method of the Random class to generate a random integer between 0 and 50. Also, use the nextDouble() method of the same class to get a random double number between 0.0 and 1.0. Finally, print the randomly generated integer and double value on the console:
2. java.util.concurrent.ThreadLocalRandom Class
The ThreadLocalRandom class of the “java.util.concurrent” package generates a random number isolated to the current thread. It can generate a random number of different types like int, boolean, double, etc. For example, the below code uses these methods to generate the respective random values:
import java.util.concurrent.ThreadLocalRandom;
public class JavaRandomNumbers {
public static void main(String args[]) {
int randomInt = ThreadLocalRandom.current().nextInt();
System.out.println("The Random Integer is ==> " + randomInt);
double randomDub = ThreadLocalRandom.current().nextDouble();
System.out.println("The Random Double is ==> " + randomDub);
boolean randomBool = ThreadLocalRandom.current().nextBoolean();
System.out.println("The Random Boolean is ==> " + randomBool);
}
}
The output confirms that the “nextInt()”, “nextDouble()”, and “nextBoolean()” methods retrieve a random integer, double, and a Boolean value:
That’s all about generating random numbers in Java using the Math.random() method.
Final Thoughts
“Math.random()” is a built-in static method of the “java.util.Math” class that generates a pseudorandom number between the range “0.0” and “1.0”. The return type of this method is double, however, it can be typecasted to other valid data types like int or long. Moreover, if you want to get/generate a random number between any range (i.e., other than 0.0 – 1.0), you can multiply the output of the random() method by the size/magnitude of the range.
This blog has comprehensively explained the working of the “Math.random()” method using different examples. Also, it has illustrated a couple of useful alternatives to the “Math.random()” method.