Java Math random

random() returns a double value greater than or equal to 0 and less than 1.0.

Following is the syntax of random() method.

double n = random()

random() method uses the pseudo-random number generator function java.util.Random().

Example 1 Mathrandom

In the following example, we use random function to generate a random number in the range [0.0, 1.0).

Java Program

public class MathExample {
	public static void main(String[] args) {
		double n = Math.random();
		System.out.println(n);
	}
}

Output

0.8503998521780656

Example 2 Mathrandom Generate Random Double from min, max

You can use random() method to generate a random number between a given minimum and a maximum.

In the following program, we will generate a random double number in the range [min, max).

Java Program

public class MathExample {
	public static void main(String[] args) {
		double min = 2.65;
		double max = 8.693;
		double n = min + (max-min)*Math.random();
		System.out.println(n);
	}
}

Output

4.723410184654693

Example 3 Mathrandom Random Integer in min, max

If any of the base or height is infinite, then the length of hypotenuse is infinite, and random() returns positive infinite.

Java Program

public class MathExample {
	public static void main(String[] args) {
		int min = 20;
		int max = 80;
		int n = (int) (min + (max-min)*Math.random());
		System.out.println(n);
	}
}

Output

34

Conclusion

In this Java Tutorial, we learned about Java Math.random() function, with example programs.