Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the RandomUtils.nextBoolean() in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The nextBoolean() static method of the RandomUtils class in Java will return a random boolean value.

Import RandomUtils

RandomUtils is defined in the Apache Commons Lang package. Apache Commons Lang can be added to the Maven project by adding the following dependency to the pom.xml file.

<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-lang3</artifactId>
   <version>3.12.0</version>
</dependency>

For other versions of the commons-lang package, refer to the Maven Repository.

Syntax

The syntax of the nextBoolean() method is as follows:

public static boolean nextBoolean()

Argument

The nextBoolean() method doesn’t take any argument.

Return value

This method randomly returns either true or false.

Code

In the code below, we have used the nextBoolean() method as follows:

import org.apache.commons.lang3.RandomUtils;
class NextBooleanExample {
public static void main( String args[] ) {
System.out.println("RandomUtils.nextBoolean() => " + RandomUtils.nextBoolean()); // the random boolean
System.out.println("RandomUtils.nextBoolean() => " + RandomUtils.nextBoolean()); // the random boolean
}
}

Explanation

In the above code:

  • On line 1, we import the RandomUtils class.
import org.apache.commons.lang3.RandomUtils;
  • On lines 5 and 6, we use the nextBoolean() method to get the random boolean value, i.e., either true or false, which is displayed accordingly.

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring