If an operator fulfilling all conditions

This may be a dumb question, but I wonder if it is possible to have an if statement that fulfills all the conditions. I explain:

if (methodA() && methodB() && methodC()) {code} 

code is executed when all three methods return true. The fact is that when a method returns false, the rest of the methods are not executed. This is usually good for performance, but what if I really need to execute all the methods no matter what they return, and after that evaluate the expression and switch to if or not. The same applies for OR or any other

Is there any way to say that java behaves like this? My current job is to divide it into three parts, but it doesn’t always do the trick and it looks really ugly.

+6
source share
8 answers

It's pretty simple: use & instead of && .

From: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.23

The conditional and operator are && ( Β§15.22.2 ), but evaluates its right operand only if the value of its left operand is true.

+24
source

Use the bitwise operator & , which evaluates both sides of the condition and stops the condition from shorting. As you noticed, the conditional operators && and || will be locked as soon as the result of the expression can be determined.

 if (methodA() & methodB() & methodC()) {code} 

Documentation

+9
source

Instead of logical AND (&&) you should use the bitwise AND (&) operator.

 if (methodA() & methodB() & methodC()) {code} 

Read more here .

+2
source

Your correct answer:

 if (methodA() & methodB() & methodC()) {code} 
+2
source

try it

 & is bitwise. && is logical. & evaluates both sides of the operation. && evaluates the left side of the operation, if it true, it continues and evaluates the right side. 

for quick use of && & if (methodA () and methodB () and methodC ()) {code}

+2
source

Just change && to & . So your answer

 if (methodA() & methodB() & methodC()) {code} 

&& is a comparison. This means that the if first check the condition methodA() && methodB() . If this returns false, then methodC() will not execute. If true, then it will be checked using the methodC() function.

& is bitwise. It will return true if all the value is 1. methodA() & methodB() & methodC() count as one comparison. Thus, it will work through the whole function. And then check if the answer is true or false.

0
source

Another solution (but not so elegant) would be to use boolean variables:

 boolean resA = methodA(); boolean resB = methodB(); boolean resC = methodC(); 

then do your ifs:

 if (resA && resB && resC) { code } 

This way your methods will be launched, and you just need to compare what they returned.

0
source

Use Bitwise And Instead Of &&

  if (methodA() & methodB() & methodC()) {code} 
-2
source

Source: https://habr.com/ru/post/958552/


All Articles