Reputation: 21
I want to ask about correct sequence "reading" of this logical expression:
(true && false | true)
I thought it returns false, because of first expression - true && false
But probably I'm doing something wrong and it's should be "reading" another way.
Can you explain what's correct way to reading it?
Upvotes: 1
Views: 89
Reputation: 1923
By keeping below the point in the notice:
All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.
This will be get executed from left to right. After that 2nd point to consider is Operator Precedence.
| is a bitwise operator and && is a logical operation. the bitwise operator has more priority than the logical operator.
In your case, the first evaluation will be false | true which is true.
then it will evaluate the true && result of above which is true.
so the given statement will be true.
Upvotes: 1
Reputation: 393956
Check the following table of Operators Precedence.
|
(bitwise inclusive OR) has higher precedence than &&
(logical AND), so false | true
is evaluated first.
That said, the evaluation order doesn't matter in your example. Both (true && false) | true
and true && (false | true)
return true
. In the first case it's false | true)
, which is true
. In the second case it's true && true
, which is also true
.
Now, here's an example where the operator precedence makes a difference:
System.out.println (false && true | true);
System.out.println (false && true || true);
|
has a higher precedence than &&
, but &&
has a higher precedence than ||
.
Therefore these expressions are evaluated as:
System.out.println (false && (true | true));
System.out.println ((false && true) || true);
As a result, the first returns false
and the second returns true
.
Upvotes: 1