Reputation: 21
cond && cond op cond
op
can be &&
or ||
Qn- For short circuit (&&
) operator if the first cond is false then right part (whole) is not evaluated or just the second cond after &&
is not evaluated
Also why the result of following two expressions different?
(2 > 3 && 5 < 2 || 3 > 2)
=> True
(2 > 3 && 5 < 2 | 3 > 2)
=> False
Can't we use short circuit operator and standard operators in a single expression...?
Upvotes: 2
Views: 3584
Reputation: 500357
The results are different because |
and ||
have different precedence.
Specifically, |
has higher precedence than &&
, whereas ||
has lower precedence than &&
.
System.out.println(2 > 3 && 5 < 2 || 3 > 2); // true
System.out.println(2 > 3 && 5 < 2 | 3 > 2); // false
System.out.println(2 > 3 && (5 < 2 | 3 > 2)); // false
System.out.println((2 > 3 && 5 < 2) | (3 > 2)); // true
Upvotes: 3
Reputation: 3830
Your results differ because your second case uses | instead of ||. | is the bit-wise or, which is different from the logical or.
Now you say short-circuit expressions vs. standard expressions, but in many languages short-circuit expressions are the default (or only way) logical expressions are evaluated.
If by "standard" you mean bit-wise operators like & or |, then you can mix and match them with logical operators, although the results may not be what you expect.
Upvotes: 1