Java Random nextBoolean() Method
Example
Flip a coin, and print "Heads" or "Tails" at random:
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rand = new Random();
if (rand.nextBoolean()) {
System.out.println("Heads");
} else {
System.out.println("Tails");
}
}
}
Note: The output is Heads or Tails. It can change each time you run the program.
Definition and Usage
The nextBoolean() method returns true or false at random. Both values have the same chance.
Use it for choices with two options, like a coin flip.
Syntax
public boolean nextBoolean()
Parameter Values
None.
Technical Details
| Returns: | true or false, at random. |
|---|
Related Pages
Java How To Generate Random Numbers
❮ Random Methods