Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Boolean.logicalOr method

Tags:

java

java-8

In Java 8 new methods in Boolean class have been added.

Let's just talk about one of them

public static boolean Boolean.logicalOr(boolean a , boolean b)

Now, my question is, Why were they needed?

What's the difference between the following two cases.

boolean result = a || b; or Boolean result = Boolean.logicalOr(a,b);

What's so special about Boolean.logicalOr() and when should I prefer one over the other.

like image 366
Shubham Batra Avatar asked Jan 19 '17 08:01

Shubham Batra


People also ask

How do you return a string in a Boolean method?

toString(boolean b) returns a String object representing the specified boolean. If the specified boolean is true, then the string "true" will be returned, otherwise the string "false" will be returned.

How do you return a Boolean value in Java?

String toString() : This method returns a String object representing this Boolean's value. If this object represents the value true, a string equal to “true” is returned. Otherwise, the string “false” is returned. int hashCode() : This method returns a hash code for this Boolean object.

Can Boolean be null?

boolean is a primitive type, and therefore can not be null.


1 Answers

Mainly those methods are there for your convenience and to make the code more readable by using the method references in lambdas/streams. Let's look at an example:

Stream.of(/* .. some objects .. */)       .map(/* some function that returns a boolean */)       .reduce(Boolean::logicalOr); 

trying to write this with a || b:

Stream.of(...)       .map(...)       .reduce((a, b) -> a || b); // logicalOr is actually using || 

not that readable, right?

As Sotirios Delimanolis stated in the comment, you may also want to have a look at the javadoc and follow @see BinaryOperator. Or have a look at the function package summary javadoc.

like image 190
Roland Avatar answered Sep 19 '22 19:09

Roland