Reputation: 320
Is it okay to use bitwise operators (|, ^, &) like this:
int a=23;
int b=42;
if(a==20^b==40){...};
Though in "Java, A Beginner's Guide" by H.Schildt it says that operators like this are equally logical and bitwise.
Upvotes: 0
Views: 874
Reputation: 3117
Yes you can, but I don't think you should.
Make sure your code reflects what you intend to do. Java has a native boolean
type which will work on true
or false
values. You can combine them with the logical &&
("and"), ||
("or") and also use the unary-!
("not"), and all comparison-operators.
When you are using these operators, you are telling that you are checking conditions.
Bit-operators, on the other hand, are working with integer-types (namely byte
, short
, int
, long
). By using them on these types, you are telling that you are performing computation.
Even though it is possible for you to use bit-operator instead of logical-operators, it is harder for code maintainer to figure out what was your intention.
Upvotes: 2
Reputation: 719436
Yes it is OK to use the logical operators like that.
Note, that they are only bitwise operators if the operands are integer types. In your example code, the operands are boolean
(the results of a==20
and b==40
) ... so that means that the operator is a logical operator not a bitwise operator.
(And if you think I'm being pedantic, consider a + b
where a
and b
are String
objects. We don't call the +
operator "addition" in that context.)
Upvotes: 0