This post will discuss how to generate a random float in Java.

1. Using Math.random() method

The standard solution to generate a pseudorandom double value is using the Math.random() method. It returns a uniformly distributed value within the range [0.0, 1.0), which represents greater than or equal to 0.0 and less than 1.0.

Download  Run Code

 
You can easily extend the solution to any valid range [min, max], as shown below:

Download  Run Code

2. Using Random.nextDouble() method

Alternatively, you can use the Random.nextDouble() method to generate a pseudorandom uniformly-distributed double value between 0.0 and 1.0 with a random number generator (RNG). Note that, 0.0d is inclusive and 1.0d is exclusive.

Download  Run Code

 
You may use the SecureRandom class, to get a cryptographically secure random number generator.

Download  Run Code

 
To get the pseudorandom uniformly-distributed double value in range [min, max], do like:

Download  Run Code

3. Using Random.nextFloat() method

Similar to the nextDouble method, the Random class contains the corresponding methods for Integer, Long, Boolean, Float, etc. To get a pseudorandom float value between 0.0f (inclusive) and 1.0f (exclusive), you can use Random.nextFloat() method.

Download  Run Code

 
As with other methods, you can easily extend the solution to work with any range:

Download  Run Code

That’s all about generating a random float in Java.