The java.lang.Math.random() method returns a pseudorandom double type number greater than or equal to 0.0 and less than 1.0. When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression new java.util.Random.
Declaration of Java Math random()
Below is the declaration of java.lang.Math.random() method is mentioned below:
public static double random()
Return Type
This method returns a pseudorandom double greater than or equal to 0.0 and less than 1.0.
Java Math random() Method with Examples
Example 1:To show the working of java.lang.Math.random() method.
java
import java.lang.Math;
class Gfg1 {
public static void main(String args[])
{
double rand = Math.random();
System.out.println("Random Number:" + rand);
}
}
|
Output:
0.5568515217910215
Example 2:To show the working of java.lang.Math.random() method.
Now to get random integer numbers from a given fixed range, we take a min and max variable to define the range for our random numbers, both min and max are inclusive in the range.
java
import java.lang.Math;
class Gfg2 {
public static void main(String args[])
{
int max = 10;
int min = 1;
int range = max - min + 1;
for (int i = 0; i < 10; i++) {
int rand = (int)(Math.random() * range) + min;
System.out.println(rand);
}
}
}
|
Output:
6
8
10
10
5
3
6
10
4
2
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
22 May, 2023
Like Article
Save Article