Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I not use the Java Shortcut Operator &

My understanding is that when using && as an mathematical operation in Java, if the LHS (Left Hand Side) of an evaluation fails, the right hand side will not be checked, so.

false && getName();

getName() would never be called as the LHS has already failed.

false & getName();

When would I ever want to check the RHS if I know the LHS has failed? Surely any dependency on the RHS evaluation being ran would be bad coding practice?

Thank you

like image 667
david99world Avatar asked Dec 16 '22 22:12

david99world


1 Answers

Well the reason for & and && is not, that one evaluates the right side and the other doesn't.

  • & is a bitwise operator, which makes a bitwise AND of the two values. It returns a value.

    Theoretically, if all bits of the left side are 0 (as is the case for false), the right side must not neccessarily be evaluated. I guess it's a design decision that it is evaluated in every case. In the simple cases, it is faster than checking if the left side is 0.

  • && is a conditional logical operator, which takes two booleans and returns a boolean (that is true if and only if both sides are true).

    The same applies here, if the left side is false, we don't need to check the right side. Here the decision was taken to skip the evaluation of the right side in that case.

And to answer your last question (when would you want to evaluate the RHS if the LHS has failed), there are some scenarios where it can be ok. However, in any case it is possible to prevent these situations (see jocelyn's answer for a good way to make sure that both expressions are evaluated) without loosing readability. In fact, I think jocelyn's way is more readable than if (exprA() & exprB()) { ... }.

Personally I never use & unless I really need a bitwise AND.

like image 133
brimborium Avatar answered Dec 31 '22 12:12

brimborium