Generating a Random Boolean Value in Java

You can opt to revamp your problem by having two arrays of integers, where one will hold the true values and the other will hold the false values. Another option is to create an extra integer array that will only store the indices of the false values. Then, you can use the aforementioned array to access and obtain a random false value.


Solution 1:

The functionality already exists in the class

java.util.Random

.

public boolean getRandomBoolean() {
    Random random = new Random();
    return random.nextBoolean();
}

Rather than repeatedly generating a new

Random

instance for every random boolean you require, it is better to create an attribute of type

Random

in your class that necessitates the random boolean. This way, you can utilize the same instance for each new random boolean.

public class YourClass {
    /* Oher stuff here */
    private Random random;
    public YourClass() {
        // ...
        random = new Random();
    }
    public boolean getRandomBoolean() {
        return random.nextBoolean();
    }
    /* More stuff here */
}


Solution 2:


The output of

(Math.random() < 0.5)

is either true or false, selected at random.


Solution 3:

This should do:

public boolean randomBoolean(){
    return Math.random() < 0.5;
}

Frequently Asked Questions