nextInt
is a static method that can be used to generate random int
values. There are two variations of the method:
Integer.MAX_VALUE
.0
Integer.MAX_VALUE
The method that doesn’t accept any parameters is used here to generate a random integer value.
32
100
The parameterized method is used here to generate a random integer value. The method accepts the lower and upper bounds as parameters.
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 int nextInt()
The method takes no parameters.
The method returns a random int value within zero to Integer.MAX_VALUE
.
public static int nextInt(int startInclusive, int endExclusive)
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.nextInt
returns a random integer value within the given range.
if
startInclusive
is greater thanendExclusive
or ifstartInclusive
is negative than function throws IllegalArgumentException
.
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());}}
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.