Java Reference
In-Depth Information
int begin2 = i2;
while (++i1 < array1.length &&
++i2 < array2.length &&
array1[i1] == array2[i2]) {
// Arrays match so far
}
int end1 = i1;
int end2 = i2;
assert end1 - begin1 == end2 - begin2;
}
The problem with this code is that when the first condition in the
while
loop fails, the
secondconditiondoesnotexecute.Thatis,once
i1
hasreached
array1.length
,theloop
terminatesafter
i1
isincremented.Consequently,theapparentrangeover
array1
islarger
than the apparent range over
array2
, causing the final assertion to fail.
Compliant Solution (Use
&
)
This compliant solution mitigates the problem by judiciously using
&
, which guarantees
that both
i1
and
i2
are incremented, regardless of the outcome of the first condition:
public void exampleFuntion() {
while (++i1 < array1.length &
// Not &&
++i2 < array2.length &&
array1[i1] == array2[i2]){
// Do something
}
}
Applicability
Failure to understand the behavior of the bitwise and conditional operators can cause un-
intended program behavior.
Bibliography
[Flanagan 2005]
§2.5.6., “Boolean Operators”
[JLS 2013]
§15.23, “Conditional-And Operator
&&
”