Close

Java - Math.random() Examples

Java Java API 


Class:

java.lang.Math

java.lang.Objectjava.lang.Objectjava.lang.Mathjava.lang.MathLogicBig

Method:

public static double random()

Returns a random double value with a positive sign, greater than or equal to 0.0 and less than 1.0.


Examples


package com.logicbig.example.math;

public class RandomExample {

public static void main(String... args) {
double result = Math.random();
System.out.printf("Math.random() = %s%n", result);
}
}

Output

Math.random() = 0.1712512196384075




Finding Random number between a range

package com.logicbig.example.math;

public class RandomExample2 {

public static void main(String... args) {
range(3.0, 5.0);
range(29.0, 29.5);
range(102.5, 105.0);
range(-289.7, 1.0);
range(0.0, 25.0);
}

private static void range(double x, double y) {
double result = Math.random() * (y - x) + x;
System.out.printf("Random Number between %s and %s = %.2f%n", x, y, result);
}
}

Output

Random Number between 3.0 and 5.0 = 4.19
Random Number between 29.0 and 29.5 = 29.01
Random Number between 102.5 and 105.0 = 103.93
Random Number between -289.7 and 1.0 = -201.55
Random Number between 0.0 and 25.0 = 1.51




See Also