What is the RandomUtils.nextBoolean() in Java?
The nextBoolean() static method of the RandomUtils class in Java will return a random boolean value.
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>
For other versions of the
commons-langpackage, refer to the Maven Repository.
Syntax
The syntax of the nextBoolean() method is as follows:
public static boolean nextBoolean()
Argument
The nextBoolean() method doesn’t take any argument.
Return value
This method randomly returns either true or false.
Code
In the code below, we have used the nextBoolean() method as follows:
import org.apache.commons.lang3.RandomUtils;class NextBooleanExample {public static void main( String args[] ) {System.out.println("RandomUtils.nextBoolean() => " + RandomUtils.nextBoolean()); // the random booleanSystem.out.println("RandomUtils.nextBoolean() => " + RandomUtils.nextBoolean()); // the random boolean}}
Explanation
In the above code:
- On line 1, we import the
RandomUtilsclass.
import org.apache.commons.lang3.RandomUtils;
- On lines 5 and 6, we use the
nextBoolean()method to get the randombooleanvalue, i.e., eithertrueorfalse, which is displayed accordingly.