How to use Math.Random in Java

Syntax:


double random = Math.random();

Java provides the static method Math.random that return a random number between 0 and 1.

Example:

The random number returned by the api is between 0 and 1. It can be converted to any range by multiplying it by a constant.

public class Math_random {

    public static void main(String[] argv) {
	
	
	double random = Math.random();
	System.out.println( "random = " + random );

	System.out.println( "from 0 to 100 = " + (random * 100) );
	
    }

}

The output will be:

random = 0.2438359361342064
from 0 to 100 = 24.38359361342064

Math.random uses a basic random algorithm that is not secure. It is recommended to use SecureRandom that provides a cryptographically strong random number generator.

References:

Java String Java SecureRandom