java Random nextBoolean() Method



Description

The java Random nextBoolean() method is used to get the next pseudorandom, uniformly distributed boolean value from this random number generator's sequence.

Declaration

Following is the declaration for java.util.Random.nextBoolean() method.

public boolean nextBoolean()

Parameters

NA

Return Value

The method call returns the next pseudorandom, uniformly distributed boolean value.

Exception

NA

Getting a Random Boolean Value Example

The following example shows the usage of Java Random nextBoolean() method. Firstly, we've created a Random object and then using nextBoolean() we retrieved a random boolean value and printed it.

package com.tutorialspoint;

import java.util.Random;

public class RandomDemo {
   public static void main( String args[] ) {
      
      // create random object
      Random randomNo = new Random();

      // get next next boolean value 
      boolean value = randomNo.nextBoolean();

      // check the value  
      System.out.println("Value is: " + value);
   }     
}

Output

Let us compile and run the above program, this will produce the following result.

Value is: true

Getting a Random Boolean Value Using a Given Seed Example

The following example shows the usage of Java Random nextBoolean() method. Firstly, we've created a Random object with a seed value and then using nextBoolean() we retrieved a random boolean and printed it.

package com.tutorialspoint;

import java.util.Random;

public class RandomDemo {
   public static void main( String args[] ) {
      
      // create random object
      Random randomNo = new Random(10);

      // get next next boolean value 
      boolean value = randomNo.nextBoolean();

      // check the value  
      System.out.println("Value is: " + value);
   }     
}

Output

Let us compile and run the above program, this will produce the following result.

Value is: true
java_util_random.htm
Advertisements