How to use RandomUtils to generate random integer values in Java
nextInt is a static method that can be used to generate random int values. There are two variations of the method:
- One generates random integer values within zero to
Integer.MAX_VALUE. - The other takes the range as parameters and generates random integer values within the specified range.
Examples
Example 1
- lower bound -
0 - upper bound -
Integer.MAX_VALUE
The method that doesn’t accept any parameters is used here to generate a random integer value.
Example 2
- lower bound -
32 - upper bound -
100
The parameterized method is used here to generate a random integer value. The method accepts the lower and upper bounds as parameters.
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;
Variant 1
# Syntax
public static int nextInt()
Parameters
The method takes no parameters.
Return value
The method returns a random int value within zero to Integer.MAX_VALUE.
Variant 2
Syntax
public static int nextInt(int startInclusive, int 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
nextInt returns a random integer value within the given range.
if
startInclusiveis greater thanendExclusiveor ifstartInclusiveis negative than function throws IllegalArgumentException.
Code
import org.apache.commons.lang3.RandomUtils;public class Main {public static void main(String[] args) {int lowerBound = 32;int upperBound = 100;System.out.printf("Random integer generated between [%s, %s) is %s", lowerBound, upperBound, RandomUtils.nextInt(lowerBound, upperBound));System.out.printf("\nRandom integer generated between [0, Integer.MAX_VALUE) is %s", RandomUtils.nextInt());}}
Expected output
Random integer generated between [32, 100) is 33
Random integer generated between [0, Integer.MAX_VALUE) is 1703546462
When you run the code, your output can be different because a random number is generated.