Java Reference
In-Depth Information
The bitwise AND and OR operators ( & and | ) lack short-circuit behavior. Similar to
most Java operators, they evaluate both operands. They return the same Boolean results
as && and || respectively,butcanhavedifferentoveralleffectsdependingonthepresence
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.
Noncompliant Code Example (Improper & )
This noncompliant code example, derived from Flanagan [Flanagan 2005], has two vari-
ables with unknown values. The code must validate its data, and then check whether ar-
ray[i] is a valid index.
Click here to view code image
int array[]; // May be null
int i; // May be an invalid index for array
if (array != null & i >= 0 &
i < array.length & array[i] >= 0) {
// Use array
} else {
// Handle error
}
This code can fail as a result of the same errors it is trying to prevent. When array
is NULL or i is not a valid index, the reference to array and array[i] will cause either
a NullPointerException or an ArrayIndexOutOfBoundsException to be thrown. The
exception occurs because the & operator fails to prevent evaluation of its right operand,
even when evaluation of its left operand proves that the right operand is inconsequential.
Compliant Solution (Use && )
Thiscompliantsolutionmitigatestheproblembyusing && ,whichcausestheevaluationof
the conditional expression to terminate immediately if any of the conditions fail, thereby
preventing a runtime exception:
Click here to view code image
int array[]; // May be null
int i; // May be an invalid index for array
if (array != null && i >= 0 &&
Search WWH ::




Custom Search