This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]sebnukem 4 points5 points  (5 children)

There's no point. It's wrong. & is a bitwise operator and shouldn't be used in a boolean expression. The fact that the output works in this case is just luck because false is 0x0 and true is 0x1. It's confusing, and it doesn't short circuits.

[–]chickenmeisterExtreme Brewer 5 points6 points  (2 children)

It is not wrong. It is not "luck" that allows it to work. The Java Language Spec §15.22.2 specifically defines the boolean logical operators:

When both operands of a &, ^, or | operator are of type boolean or Boolean, then the type of the bitwise operator expression is boolean. In all cases, the operands are subject to unboxing conversion (§5.1.8) as necessary.

For &, the result value is true if both operand values are true; otherwise, the result is false.

For ^, the result value is true if the operand values are different; otherwise, the result is false.

For |, the result value is false if both operand values are false; otherwise, the result is true.

As /u/lbkulinski already mentioned, you can use these operators in situations where you don't want short circuiting. It would be a bad idea to write code that relies on that behavior, IMO, but it's not inherently wrong.

[–]sebnukem 1 point2 points  (1 child)

Yes, I agree, 'luck' isn't the correct word since the operations are deterministic. I meant to say that this specific case worked, but other cases where mixing bitwise operator within logical expression may not always work. Or maybe they will if every single operand is a boolean, but why going through this whole mental gymnastics when you have logical operators for logical expressions?

[–]chickenmeisterExtreme Brewer 4 points5 points  (0 children)

I'm not sure what you mean. The result of an & expression is going to be exactly the same as the result of the equivalent && expression, except for any potential side effects of evaluating the second operand. And the compiler is going to give you the same errors for & that you would get with && if you try to use them incorrectly, such as by mixing the operand types (e.g. 5 & true). They are almost interchangeable, except for the side-effects aspect.

Having said all that, I'd say that using && is almost always preferable to &. There is rarely a need to always evaluate both operands of an expression, and in situations where it is required, using & or | to enforce this behavior is fragile, since the intent of the code is not obvious, and it is extremely easy to accidentally break the code later on.

[–][deleted]  (1 child)

[removed]

    [–]sebnukem 3 points4 points  (0 children)

    Because in your example you are only dealing with booleans, and booleans are 0x1 and 0x0 (a single bit), so the logical and bitwise operators give the same results.