Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The conditional AND and OR operators (&& and ||, respectively) exhibit short-circuit behavior. That is, the second operand is evaluated only when the result of the conditional operator cannot be deduced solely by evaluating the first operand. Consequently, when the result of the conditional operator can be deduced solely from the result of the first operand, the second operand will remain unevaluated; its side - effects, if any, will never occur.

The bitwise AND and OR operators (& and |) do not exhibit this behavior. Like most other Java operators, they evaluate both operands, first the left operand, and then the right. They return the same Boolean result as && and ||, respectively, but can have different overall effect effects depending on the presence or absence of side-effects in the second operand.

Consequently, either the & or the && operator can be used when performing Boolean logic. However, there are times when the short-circuiting behavior is preferred , and other times when the short-circuiting behavior causes subtle bugs.

...

This compliant solution uses multiple if statements to achieve the proper effect. While correct, it is more verbose and may could be more difficult to maintain.

...

This noncompliant code example demonstrates code that compares two arrays for ranges of members that match. Here i1 and i2 are valid array indices in array1 and array2, respectively. It is expected that end1 and end2 will point to the end of the matching ranges in the two arrays.

...

The problem with this code is that when the first condition in the while loop fails, the second condition is not executed. That is, once i1 has reached array1.length, the loop may could terminate after i1 is executed. Consequently, the range over array1 is larger than the range over array2, causing the final assertion to fail.

...

CERT C Secure Coding Standard: "EXP02-C. Be aware of the short-circuit behavior of the logical AND and OR operators"
CERT C++ Secure Coding Standard: "EXP02-CPP. Be aware of the short-circuit behavior of the logical AND and OR operators"

Bibliography

Wiki Markup
\[[Flanagan 2005|AA. Bibliography#Flanagan 05]\] 2.5.6. Boolean Operators
\[[JLS 2005|AA. Bibliography#JLS 05]\] Sections [15§15.23|http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.23] "Conditional-And Operator &&" and [15§15.24|http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.24] "Conditional-Or Operator ||"

...