Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

How to use RandomUtils to generate random double values in Java

abhilash

Overview

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:

  • One generates random double values within zero to Double.MAX_VALUE.
  • The other takes the range as parameters and generates random double values within the specified range.

How to import 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;

Syntax

public static double nextDouble(final double startInclusive, final double endExclusive)

Parameters

  • startInclusive - the lower bound of the range or the smallest value that can be returned
  • endExclusive - the upper bound of the range that is not included

Return value

nextDouble returns a random double value within the given range.


public static double nextDouble()

Parameters

The method takes no parameters.

Return value

The method returns a random double value within zero to Double.MAX_VALUE.

Code

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());
    }
}

Example 1

  • lower bound - 100.4
  • upper bound - 101.4

The parameterized method is used here to generate a random double value. The method accepts the lower and upper bounds as parameters.

Example 2

  • lower bound - 0
  • upper bound - Double.MAX_VALUE

The method that doesn’t accept any parameters is used here to generate a random double value.

Expected output

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.

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring