Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If with multiple &&, || conditions Evaluation in java

if(a && b || c || d || e)

whether it check (a && b), if a and b must be true always, then only allow inside ? or

((a && b) || a && c || a && d || a && e)), any of the condition is true will it allow inside ?

like image 805
Abish R Avatar asked Dec 23 '15 05:12

Abish R


1 Answers

If I understand you correctly, in the first part of your question, you are asking whether a and b must both be true for the entire expression (a && b || c || d || e) to evaluate as true.

The answer to that question is no. Java operators are such that && has higher precedence than ||. So the equivalent expression is:

(a && b) || c || d || e

Therefore the expression as a whole will evaluate to true if any of a && b or c or d or e is true. For example, if a was false and c was true, the expression as a whole is true.

Note that Java conditional operators short-circuit. This means that once the end result of the expression is known, evaluation stops. For example, if a and b were both true, meaning the overall expression must evaluate to true, then c, d and e are not evaluated.

For the second part of your question, we can apply the same logic. The equivalent expression is therefore:

(a && b) || (a && c) || (a && d) || (a && e)

This will evaluate to true if any of the sub-components, eg. a && c evaluates to true. As others have noted, a must be true for the expression to be true as it is part of every sub-component. Then if any of the other variables is true, the expression is true.

Once you understand that, you can see how the simplification of this expression suggested by @Arc676 is arrived at:

a && (b || c || d || e)

I should also add that the two expressions in your question are different logically. They are equivalent to:

(a && b) || c || d || e

and

a && (b || c || d || e)

The parentheses affect the order of evaluation. In the first, a and b are grouped together by an &&, hence both must be true for that part of the expression (in the parentheses) to be true. In the second, b, c, d and e are grouped together by ||. In this case, only one of b, c, d and e needs to be true for that part of the expression (in the parentheses) to be true.

like image 123
dave Avatar answered Sep 19 '22 16:09

dave