Java Math random() Method
The random() method of Math class returns a double value with a positive sign, less than 1 and greater than or equal to 0.0. This method is properly synchronized with the correct use of one or more thread.
Syntax:
public static double random ()
Return Value:
The random() method returns a pseudorandom double value less than 1 and greater than or equal to 0.0.
Example 1:
public class JavaMathRandomExample1 {
static int i=1;
public static void main(String[] args) {
// generate random number
double a = Math.random();
double b = Math.random();
// Output generated is random and different for every code
System.out.println(i++ +". Random value : "+ a);
System.out.println(i++ +". Random value : "+b);
}
}
Output:
Random value : 0.5940972537310859 Random value : 0.07044302938090907
Example 2:
public class JavaMathRandomExample2 {
static int i=1;
public static void main(String[] args) {
// generate random number
double a = Math.random()*Double.NaN;
// Output generated will be NaN
System.out.println(i++ +". Random value : "+ a);
}
}
Output:
Random value : NaN
Example 3:
public class JavaMathRandomExample3 {
static int i=1;
public static void main(String[] args) {
// generate random number
double a = Math.random()*Double.POSITIVE_INFINITY;
// Output generated will be infinity
System.out.println(i++ +". Random value : "+ a);
}
}
Output:
Random value : Infinity
Example 4:
public class JavaMathRandomExample4 {
static int i=1;
public static void main(String[] args) {
// generate random number
double a = Math.random()/Double.NEGATIVE_INFINITY;
// Output generated will be -0.0
System.out.println(i++ +". Random value : "+ a);
}
}
Output:
Random value : -0.0
