Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If statement executing all conditions

This may actually be a silly question but I am wondering if it is possible to have an if statement executing all conditions. I explain:

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

code is executed when all three methods return true. The point is that when a method returns false, the rest of the methods aren't executed. This is normally a good thing for performance but what if I really need to execute all methods independently of what they are returning and after that evaluate the expression and go into the if or not. The same is applied for OR or whatever

Is there a way to tell java to behave that way? My current work around is to split it in three ifs but this not always does the trick and looks really ugly.

like image 944
iberbeu Avatar asked Nov 21 '13 10:11

iberbeu


2 Answers

That’s quite simple: use the & operator instead of &&.

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

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

like image 106
Holger Avatar answered Sep 18 '22 13:09

Holger


Use the bitwise & operator, which evaluates both sides of the condition and stops the conditional from short circuiting. As you have noticed the && and || conditional operators will short circuit once the result of the expression can be determined.

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

Documentation

like image 35
Kevin Bowersox Avatar answered Sep 17 '22 13:09

Kevin Bowersox