Reputation: 177
I just practice some basic Java practice problems and this below shows up.
if((b2 = false) | (21 % 5)>2) return true;
So b2 is assigned with false and 1 > 2 is certainly false, but how do we evaluate "|" ? should it return true?
Upvotes: 1
Views: 135
Reputation: 59096
b2 = false
assigns false
to the variable b2
, and the expression has the value false
. |
on booleans means "or" (without short-circuit), so it evaluates both operands, and the outcome is true if either operand is true.
It is not a bitwise operator. If you use |
on integers, it is a bitwise operator. If you use |
on booleans, it is a logical operator.
Edit:
||
is a short-circuit operator. If you write (a() || b())
, and a()
evaluates to true, then b()
will not be evaluated, because the result of the or must be true. Single |
does not short-circuit, so both operands are always evaluated.
Upvotes: 2
Reputation: 10652
(b2 = false)
(Edited after khelwood's correction) This is also an assignment, not just a logical operation, so be careful for side effects.
And yes, for a boolean, "|" is "or" (and not bitwise), so if the first operator is true, it will always be true.
Upvotes: 1