Generate Random Boolean in Java



In order to generate Random boolean in Java, we use the nextBoolean() method of the java.util.Random class. This returns the next random boolean value from the random generator sequence.

Declaration −The java.util.Random.nextBoolean() method is declared as follows −

public boolean nextBoolean()

Let us see a program to generate random boolean in Java −

Example

 Live Demo

import java.util.Random;
public class Example {
   public static void main(String[] args) {
      Random rd = new Random(); // creating Random object
      System.out.println(rd.nextBoolean()); // displaying a random boolean
   }
}

Output

true

Note − The output might vary on Online Compilers.

Updated on: 2020-06-29T06:14:19+05:30

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements