You can generate random double
values with the nextDouble
method of the RandomUtils
class.
nextDouble
is a static method that can be used to generate random double
values. There are two variations of the method:
Double.MAX_VALUE
.RandomUtils
RandomUtils
is defined in the Apache Commons Lang
package. Apache Commons Lang
can be added to the Maven project by adding the following dependency to the pom.xml
file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
Note: For other versions of the commons-lang package, refer to the Maven Repository.
You can import the RandomUtils
class as follows:
import org.apache.commons.lang3.RandomUtils;
public static double nextDouble(final double startInclusive, final double endExclusive)
startInclusive
- the lower bound of the range or the smallest value that can be returnedendExclusive
- the upper bound of the range that is not includednextDouble
returns a random double value within the given range.
public static double nextDouble()
The method takes no parameters.
The method returns a random double value within zero to Double.MAX_VALUE
.
import org.apache.commons.lang3.RandomUtils;public class Main {public static void main(String[] args) {double lowerBound = 100.4;double upperBound = 101.4;System.out.printf("Random double generated between [%s, %s) is %s",lowerBound, upperBound, RandomUtils.nextDouble(lowerBound, upperBound));System.out.printf("\nRandom double generated between [0, Double.MAX_VALUE) is %s", RandomUtils.nextDouble());}}
The parameterized method is used here to generate a random double value. The method accepts the lower and upper bounds as parameters.
Double.MAX_VALUE
The method that doesn’t accept any parameters is used here to generate a random double value.
Random double generated between [100.4, 101.4) is 101.13690440896326
Random double generated between [0, Double.MAX_VALUE) is 1.148809263610535E308
When you run the code, your output can be different because a random number is generated.