How to get a random Boolean value in Java

This shot explores different ways to produce random Boolean values in Java.

The nextBoolean() method of the Random class

The nextBoolean() method of the Random class is an instance method that generates pseudorandom, uniformly distributed Boolean values. True and false values are generated with approximately equal probability.

Syntax

public boolean nextBoolean()

This method has no parameters and returns a random Boolean value.

import java.util.Random;
public class Main {
public static void main(String[] args)
{
Random random = new Random();
System.out.println("Random boolean - " + random.nextBoolean());
}
}

The nextBoolean() method of the RandomUtils class

nextBoolean() is a static method in the RandomUtils class that generates random Boolean values.

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;

Syntax

public static boolean nextBoolean()

This method has no parameters and returns a random Boolean value.

Example

In the code below, we use the class name RandomUtils to call the nextBoolean() method, and get a random Boolean value.

import org.apache.commons.lang3.RandomUtils;
public class Main {
public static void main(String[] args)
{
System.out.println("Random boolean - " + RandomUtils.nextBoolean());
}
}

Free Resources