How to get random long values using RandomUtils in Java

Overview

Random long values can be generated using the nextLong method of the RandomUtils class.

nextLong is a static method that generates random long values. There are two variations of the method. They are as follows:

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

How to import RandomUtils?

RandomUtils is defined in the Apache Commons Lang package. You can add the Apache Commons Lang 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 long nextLong(final long startInclusive, final long 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

This will return a random long value within the given range.


public static long nextLong()

Parameters

The method takes no parameters.

Return value

A random long value within the range of zero to Long.MAX_VALUE.

Code

import org.apache.commons.lang3.RandomUtils;
public class Main {
public static void main(String[] args) {
long lowerBound = 100L;
long upperBound = 120L;
System.out.printf("Random Number generated between [%s, %s) is %s",lowerBound, upperBound, RandomUtils.nextLong(lowerBound, upperBound));
System.out.printf("\nRandom Number generated between [0, Long.MAX_VALUE) is %s", RandomUtils.nextLong());
}
}

Example 1

  • lower bound - 100L
  • upper bound - 120L

In line 8 of the code above, the parameterized method is used here to generate a random long value. The method accepts lower and upper bound as the parameters.

Example 2

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

In line 9 of the code above, the method which doesn’t accept parameters is used to generate a random long value.

Expected output

The output of the code above is as follows:

Random Number generated between [100, 120) is 112
Random Number generated between [0, Long.MAX_VALUE) is 2111934587352218129

When you run the code, your output can be different

Free Resources