Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

randomutils
java
communitycreator

How to generate random float values using RandomUtils in Java

abhilash

Random float values can be generated using nextFloat method of the RandomUtils class.

nextFloat is a static method that can be used to generate random float values. There are two variations of the method. They are as follows:

  • One which takes the range as parameters and generates random float values within the specified range.
  • One which generates random float values within zero to Float.MAX_VALUE

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;

Variant 1

Syntax

public static float nextFloat(float startInclusive, float 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

The function returns a random float within the specified range.

Variant 2

Syntax

A random float value within the given range.


public static float nextFloat()

Parameters

The method takes no parameters.

Return value

A random float value within zero to Float.MAX_VALUE.

Code

import org.apache.commons.lang3.RandomUtils;

public class Main {

    public static void main(String[] args) {
        float lowerBound = 100.4f;
        float upperBound = 101.4f;
        // variant 1
        System.out.printf("Random float generated between [%s, %s) is %s",lowerBound, upperBound, RandomUtils.nextFloat(lowerBound, upperBound));
        // variant 2
        System.out.printf("\nRandom float generated between [0, Float.MAX_VALUE) is %s", RandomUtils.nextFloat());
    }
}

Expected output

Random float generated between [100.4, 101.4) is 101.01888
Random float generated between [0, Double.MAX_VALUE) is 2.6434219E38

When you run the code, your output can be different

Example 1

  • lower bound - 100.4f
  • upper bound - 101.4f

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

Example 2

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

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

RELATED TAGS

randomutils
java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring