The nextBoolean()
static method of the RandomUtils
class in Java will return a random boolean
value.
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-lang
package, refer to the Maven Repository.
The syntax of the nextBoolean()
method is as follows:
public static boolean nextBoolean()
The nextBoolean()
method doesn’t take any argument.
This method randomly returns either true
or false
.
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}}
In the above code:
RandomUtils
class.import org.apache.commons.lang3.RandomUtils;
nextBoolean()
method to get the random boolean
value, i.e., either true
or false
, which is displayed accordingly.