Java Random.nextBoolean() – Examples
In this tutorial, we will learn about the Java Random.nextBoolean() method, and learn how to use this method to generate a random boolean value, with the help of examples.
nextBoolean()
Random.nextBoolean() returns the next pseudorandom, uniformly distributed boolean value from this random number generator’s sequence.
Syntax
The syntax of nextBoolean() method is
Random.nextBoolean()
Returns
The method returns boolean value.
Example 1 – nextBoolean()
In this example, we will create an object random
of Random
class type. We will call nextBoolean() on this Random object to get the next random boolean value. We shall print it to console.
Java Program
import java.util.Random;
public class Example{
public static void main(String[] args) {
Random random = new Random();
boolean b = random.nextBoolean();
System.out.println("Next random boolean value is : " + b);
}
}
Output
Next random boolean value is : true
Output may vary, since the boolean values are generated randomly.
Example 2 – nextBoolean()
In this example, we will create an object random
of Random
class type. We will call nextBoolean() on this Random object repetitively in a for loop.
Java Program
import java.util.Random;
public class Example{
public static void main(String[] args) {
Random random = new Random();
for(int i=0; i < 10; i++)
System.out.println(random.nextBoolean());
}
}
Output
true
true
false
false
true
false
false
true
false
true
Output may vary, since the boolean values are generated randomly.
Conclusion
In this Java Tutorial, we have learnt the syntax of Java Random.nextBoolean() method, and also learnt how to use this method with the help of examples.