Random().nextBoolean()
Is a method to generate random boolean values in Java. It is explained in detail below:
-
Random()
:Random
is a class in the Java standard library used to generate pseudo-random numbers.Random()
It isRandom
a no-argument constructor of the class, creating a newRandom
object. -
nextBoolean()
:nextBoolean()
isRandom
one of the methods of the class, used to generate a random Boolean value. It returns a randomboolean
value, which istrue
orfalse
. Each callnextBoolean()
to generates a new random boolean value.
import java.util.Random;
boolean success = new Random().nextBoolean();
System.out.println(success); // 输出随机的布尔值
The above code generates a random boolean value and assigns it to success
the variable. Then, System.out.println()
print out the Boolean value via the method.
Note that Random()
the constructor uses the current time as the default seed value, which means calling it multiple times within the same millisecond Random().nextBoolean()
may result in the same boolean value. If you need higher quality random numbers or need to control the generation of random numbers, you can consider using java.util.Random
other methods of the class or use java.security.SecureRandom
the class.